我想更好地理解泛型,并且正在编写一个函数,该函数在具有给定值的给定字典中查找关键字。 如果未找到该值,则应返回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'
这是值得阅读**选配的[斯威夫特语言指南]在部分**(https://developer.apple。 com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#// apple_ref/doc/uid/TP40014097-CH5-ID330) – vadian
@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