0

I have an array like this:

let strNames = ["banana", "apple", "mango"] 

I am looking for a result like this:

var abc = [Fruit(id: 0, name: "banana"), Fruit(id: 1, name: "apple"), Fruit(id: 2, name: "mango")] 

In classic way I can do so far. Can anybody please help me mapping in Swift way?

var abc: [Fruit] = [] for i in 0..<strNames.count { abc.append(Fruit(id: i, name: strNames[i])) } 
2
  • 3
    Does this answer your question? Commented Sep 21, 2020 at 0:44
  • Please include Fruit. Commented Sep 21, 2020 at 1:58

2 Answers 2

3

Initializers can be used as functions using this syntax.

["banana", "apple", "mango"].enumerated().map(Fruit.init) 

It appears that your Fruit type matches up with EnumeratedSequence.Element exactly.

struct Fruit { let id: Int let name: String } 

If it didn't, you'd just need to create your own closure.

["banana", "apple", "mango"].enumerated().map { Fruit(id: $0.offset, name: $0.element) } 
Sign up to request clarification or add additional context in comments.

Comments

1

Thank you @Sweeper for your suggestions. Actually this is what I am looking for...

let abc: [Fruit] = strNames.enumerated().map { Fruit(id: $0, name: $1) } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.