2

I have created an Array of Dictionaries:

let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]

Now I have to create an array of Name only.

What I have done is this:

var nameArray = [String]()
for dataDict in tempArray {
    nameArray.append(dataDict["Name"]!)
}

But is there any other efficient way of doing this.

1
  • try to implement getter setter so after adding data in array you can fetch the require data using loop or flap map as you like. Commented Feb 6, 2018 at 7:59

2 Answers 2

4

You can use flatMap (not map) for this, because flatMap can filter out nil values (case when dict doesn't have value for key "Name"), i.e. the names array will be defined as [String] instead of [String?]:

let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
let names = tempArray.flatMap({ $0["Name"] })
print(names) // ["ABC", "qwe", "rty", "uio"]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. your logic executed faster.
3

Use compactMap as flatMap is deprecated.

let tempArray = [["id":"1","Name":"ABC"],["id":"2","Name":"qwe"],["id":"3","Name":"rty"],["id":"4","Name":"uio"]]
let name = tempArray.compactMap({ $0["Name"]})
print(name)

enter image description here

1 Comment

@Cristik - With Xcode 9.3, Apple itself suggest replacing flatMap with compactMap. Although, you are right. Let check more detail and comparison between both, and hat should be better. Thanks for your remarks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.