我想更好地理解泛型,並且正在編寫一個函數,該函數在具有給定值的給定字典中查找關鍵字。 如果未找到該值,則應返回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