Swift: Dictionaries Inside Array

Swift: dictionaries inside array

The correct way is:

var persons = [Dictionary<String, String>]()

which is equivalent to:

var persons = [[String : String]]()

What your code does instead is to create an array filled in with an instance of Dictionary<String, String>, whereas I presume you want an empty instance of the array containing elements of Dictionary<String, String> type.

Swift - Adding value to an array inside a dictionary

EDIT: Thanks to Martin's comment. The snippet below is the the most succinct answer I can think of. I was initially coming at it from a wrong direction. and I was getting an error. See comments

struct Student { 
let id: Int
let subject : String
}

var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]

typealias Subject = String
var dict : [Int: [Subject]] = [:]

for student in studentArray {

(dict[student.id, default: []]).append(student.subject)
}

print(dict)

Previous answers:

struct Student { 
let id: Int
let subject : String
}

var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]

typealias Subject = String
var dict : [Int: [Subject]] = [:]

for student in studentArray {
var subjects = dict[student.id] ?? [String]()
subjects.append(student.subject)
dict[student.id] = subjects
}

print(dict)

Or you can do it this way:

struct Student { 
let id: Int
let subject : String
}

var studentArray = [Student(id: 1, subject: "History"), Student(id: 2, subject: "History"), Student(id:1, subject: "Maths")]

typealias Subject = String
var dict : [Int: [Subject]] = [:]

for student in studentArray {
if let _ = dict[student.id]{
dict[student.id]!.append(student.subject)
}else{
dict[student.id] = [student.subject]
}
}

print(dict)

whichever you like

Swift 3: Array to Dictionary?

I think you're looking for something like this:

extension Array {
public func toDictionary<Key: Hashable>(with selectKey: (Element) -> Key) -> [Key:Element] {
var dict = [Key:Element]()
for element in self {
dict[selectKey(element)] = element
}
return dict
}
}

You can now do:

struct Person {
var name: String
var surname: String
var identifier: String
}

let arr = [Person(name: "John", surname: "Doe", identifier: "JOD"),
Person(name: "Jane", surname: "Doe", identifier: "JAD")]
let dict = arr.toDictionary { $0.identifier }

print(dict) // Result: ["JAD": Person(name: "Jane", surname: "Doe", identifier: "JAD"), "JOD": Person(name: "John", surname: "Doe", identifier: "JOD")]

If you'd like your code to be more general, you could even add this extension on Sequence instead of Array:

extension Sequence {
public func toDictionary<Key: Hashable>(with selectKey: (Iterator.Element) -> Key) -> [Key:Iterator.Element] {
var dict: [Key:Iterator.Element] = [:]
for element in self {
dict[selectKey(element)] = element
}
return dict
}
}

Do note, that this causes the Sequence to be iterated over and could have side effects in some cases.

Swift dictionary with array as value

Yes

let myDictionary: [String: [Int]] = ["Hello": [1, 2, 3], "World": [4, 5, 6]]

In fact, you don't even need the explicit type declaration if you assign an initial value in place. It can go as simple as:

let myDictionary = ["Hello": [1, 2, 3], "World": [4, 5, 6]]

To use the value:

println(myDictionary["Hello"][0]) // Print 1
println(myDictionary["World"][0]) // Print 4

Swift : How do i create an array of dictionaries, where each dictionary contains an array inside them?

It should be declared as follows:

var natureList = [[String: Any]]()

or as @LeoDabus advised (thanks to him):

var natureList: [[String: Any]] = []

Means that natureList is an array of dictionaries of strings as keys and any as values.

If you are aiming to declare it using Dictionary -which is uanessacry-, you could also do it like this:

var natureList = [Dictionary<String, Any>]()

Check if Dictionary is inside Array of Dictionaries in Swift 3

I think the solution is more straightforward than the other answers suggest. Just use:

let newDictionary = ["keyword":"celery", "identifier": "3"]
if !suggestions.contains{ $0 == newDictionary } {
suggestions.append(newDictionary)
}

This makes sure that your existing array of dictionaries does not contain the new dictionary you want to add before appending it.

How to convert dictionary to array

You can use a for loop to iterate through the dictionary key/value pairs to construct your array:

var myDict: [String : Int] = ["attack" : 1, "defend" : 5, "block" : 12]

var arr = [String]()

for (key, value) in myDict {
arr.append("\(key) \(value)")
}

Note: Dictionaries are unordered, so the order of your array might not be what you expect.


In Swift 2 and later, this also can be done with map:

let arr = myDict.map { "\($0) \($1)" }

This can also be written as:

let arr = myDict.map { "\($0.key) \($0.value)" }

which is clearer if not as short.

How to store dictionary values into an array from array of dictionaries in swift

Hope this can help you. swift codes

    var dic_categorys : NSDictionary! // original Dictionary
//
var array_item : NSArray! = dic_categorys.valueForKey("categorys") as NSArray
if let array = array_item {

var array_list : NSMutableArray! = NSMutableArray(array:array)
var array_list_category_name : NSMutableArray = NSMutableArray()
//
for item in array_list {
var dic_item : NSDictionary! = item as NSDictionary
if let dic = dic_item {
array_list_category_name.addObject(dic.valueForKey("category_name")!)
}
}

}


Related Topics



Leave a reply



Submit