我有这段Swift代码:
guard let user = username else{
return nil
}
但是我遇到了以下错误:
Nil is incompatible with return type String
你们中有谁知道我在这种情况下为什么会返回nil或者怎样返回nil吗?
非常感谢你们的帮助。
我有这段Swift代码:
guard let user = username else{
return nil
}
但是我遇到了以下错误:
Nil is incompatible with return type String
你们中有谁知道我在这种情况下为什么会返回nil或者怎样返回nil吗?
非常感谢你们的帮助。
你的函数声明了一个可选的返回类型吗?
func foo() -> String? { ...
注意
C或Objective-C中不存在可选项(optionals)的概念。在Objective-C中最接近的是从本应返回对象的方法中返回nil,其中nil表示“没有有效对象”。
你必须告诉编译器你想返回nil
。你该怎么做呢?在你的对象后面添加?
。例如,看一下这段代码:
func newFriend(friendDictionary: [String : String]) -> Friend? {
guard let name = friendDictionary["name"], let age = friendDictionary["age"] else {
return nil
}
let address = friendDictionary["address"]
return Friend(name: name, age: age, address: address)
}
注意我需要告诉编译器,我正在返回的Friend
对象是一个可选的Friend?
。否则它会抛出一个错误。
*你的函数是否声明了可选的返回类型?
func minAndmax(array:[Int])->(min:Int, max:Int)? {
if array.isEmpty {
return nil
}
var currentMin = array[0]
var currentMax = array[0]
for value in array {
if value < currentMin {
currentMin = value
}
else if value > currentMax {
currentMax = value
}
}
return (currentMin, currentMax)
}
if let bounds = minAndmax(array: [8, -6, 2, 109, 3, 71]) {
print(bounds)
}