Map array of objects to Dictionary in Swift

前端 未结 9 520
半阙折子戏
半阙折子戏 2021-01-30 00:32

I have an array of Person\'s objects:

class Person {
   let name:String
   let position:Int
}

and the array is:

         


        
9条回答
  •  故里飘歌
    2021-01-30 01:16

    How about a KeyPath based solution?

    extension Array {
    
        func dictionary(withKey key: KeyPath, value: KeyPath) -> [Key: Value] {
            return reduce(into: [:]) { dictionary, element in
                let key = element[keyPath: key]
                let value = element[keyPath: value]
                dictionary[key] = value
            }
        }
    }
    

    This is how you will used it:

    struct HTTPHeader {
    
        let field: String, value: String
    }
    
    let headers = [
        HTTPHeader(field: "Accept", value: "application/json"),
        HTTPHeader(field: "User-Agent", value: "Safari"),
    ]
    
    let allHTTPHeaderFields = headers.dictionary(withKey: \.field, value: \.value)
    
    // allHTTPHeaderFields == ["Accept": "application/json", "User-Agent": "Safari"]
    

提交回复
热议问题