2017-07-06 41 views
1

我想更好地理解泛型,並且正在編寫一個函數,該函數在具有給定值的給定字典中查找關鍵字。 如果未找到該值,則應返回nil。無法在泛型函數中返回nil

func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key { 
    for set in dictionary { 
     if set.value == value { 
      return set.key 
     } 
    } 
    return nil //ERROR: Nil is incompatible with Type 'Key' 
} 

我reveice此錯誤:

Nil is incompatible with Type 'Key'

+1

這是值得閱讀**選配的[斯威夫特語言指南]在部分**(https://developer.apple。 com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#// apple_ref/doc/uid/TP40014097-CH5-ID330) – vadian

+0

@vadian這是值得的閱讀s̶e̶c̶t̶i̶o̶n̶̶a̶b̶o̶u̶t̶̶O̶p̶t̶i̶o̶n̶a̶̶̶̶̶̶̶̶̶̶̶[Swift語言指南](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/) – Alexander

回答

2

後添加?爲了回報爲零,你需要返回鍵可選的「Key?

你可以閱讀更多有關自選here

func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key? { 
    for set in dictionary { 
     if set.value == value { 
      return set.key 
     } 
    } 
    return nil 
} 
2

你的功能被設置爲返回Key通過-> Key

指示不能返回一個零,因爲Key是展開的變量。相反,您可以將函數設置爲返回Optional,這意味着它可以具有Key,也可以爲零。只需將返回類型

func findKey<Key, Value: Equatable>(for value: Value, in dictionary: [Key: Value]) -> Key? { 
    for set in dictionary { 
     if set.value == value { 
      return set.key 
     } 
    } 
    return nil 
} 
1

替代實現:

extension Dictionary where Value: Equatable { 
    func key(forValue v: Value) -> Key? { 
     return self.first(where: { $0.value == v})?.key 
    } 
} 

["a": 1, "b": 2, "c": 3].key(forValue: 3) // => Optional("c") 

注意,在兩個Key點地圖相同的Valuev,它不確定性這兩個Key S的將被退回的情況。要獲得所有Key映象不中Valuev,你可以這樣做:

extension Dictionary where Value: Equatable { 
    func keys(forValue v: Value) -> [Key] { 
     return self.filter{ $0.value == v}.map{ $0.key } 
    } 
} 

["a": 1, "b": 2, "c": 3, "d": 3].keys(forValue: 3) // => ["d", "c"]