2017-07-06 44 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"]