swift convert array to dictionary
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
}
}
// Example
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")]
Also in Swift:
- get hours difference between two dates swift
- number of characters in a string swift
- swift allow gesture recognizer over others
- swift file size from url
- activity indicator swiftui
- how to set return type swift
- navigationcontroller.pushviewcontroller
- changing color of background swift
- tableview cell animation swift
- swiftui foreach
- swift for loop index
- swift pdf preview image
- type String and int swift addition
- view will appear
- How do I check if a string contains another string in Swift
- swift get day from available string
- variadic parameters swift
- swift alert toast
- swift enum
- swift scrollview hide scrollbar
- Resizing UITableView to fit content
- swift comments
- loop backwards swift
- swift change button text