Swift - Convert Array to Dictionary

后端 未结 7 1517
轻奢々
轻奢々 2021-02-15 12:00

I just want convert an array of Player Names into a dictionary Scoreboard, giving everyone an initial score of 0.

Meaning...

var playerNames =          


        
相关标签:
7条回答
  • 2021-02-15 12:31

    Based on jmad8 answer

    Details

    • Swift 5.3
    • Xcode 12.0.1 (12A7300)

    Solution

    extension Sequence {
        func toDictionary<Key: Hashable, Value>(where closure: (Element) -> (Key, Value)) -> [Key: Value] {
            reduce(into: [Key: Value]()) { (result, element) in
                let components = closure(element)
                result[components.0] = components.1
            }
        }
        
        func toCompactDictionary<Key: Hashable, Value>(where closure: (Element) -> ((Key, Value)?)) -> [Key: Value] {
            reduce(into: [Key: Value]()) { (result, element) in
                guard let components = closure(element) else { return }
                result[components.0] = components.1
            }
        }
    }
    

    Usage

    // Sample 1
    
    print(languages.toDictionary { (string) -> (Character, String) in
        return (string.first!, string)
    })
    
    print(languages.toCompactDictionary { (string) -> (Character, String)? in
        guard let character = string.first, character != Character("J") else { return nil }
        return (character, string)
    })
    
    
    // Sample 2
    
    print(languages.enumerated().toDictionary { (data) -> (Int, String) in
        return (data.offset, data.element)
    })
    
    // Shorter version of sample 2
    
    print(languages.enumerated().toDictionary { ($0.offset, $0.element) })
    
    // Sample 3
    
    struct Order {
        let id: Int
        let desctiption: String
    }
    
    let orders = [
                    Order(id: 0, desctiption: "Apple"),
                    Order(id: 1, desctiption: "Banana"),
                    Order(id: 2, desctiption: "watermelon")
                ]
    
    print(orders.toDictionary { ($0.id, $0) })
    
    0 讨论(0)
提交回复
热议问题