Ios Swift:Nil与返回类型字符串不兼容
我在Swift中有此代码:Ios Swift:Nil与返回类型字符串不兼容,ios,swift,xcode7,guard,Ios,Swift,Xcode7,Guard,我在Swift中有此代码: guard let user = username else{ return nil } 但我得到了以下错误: Nil is incompatible with return type String 你们中有人知道我为什么或者如何在这种情况下返回零吗 非常感谢您的帮助您的函数是否声明了可选的返回类型 func foo()->字符串?{ 有关更多信息,请参见: 注 在C或Objective-C中不存在optionals的概念 在Objecti
guard let user = username else{
return nil
}
但我得到了以下错误:
Nil is incompatible with return type String
你们中有人知道我为什么或者如何在这种情况下返回零吗
非常感谢您的帮助您的函数是否声明了可选的返回类型 func foo()->字符串?{ 有关更多信息,请参见: 注 在C或Objective-C中不存在optionals的概念 在Objective-C中,最接近的是从 方法,否则将返回一个对象,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)
}
请注意,我需要告诉编译器,我返回的对象友元
,是一个可选的友元?
。否则它将抛出错误。*您的函数是否声明了可选的返回类型
func最小值和最大值(数组:[Int])->(最小值:Int,最大值:Int){
如果array.isEmpty{
归零
}
var currentMin=数组[0]
var currentMax=数组[0]
对于数组中的值{
如果值<当前最小值{
currentMin=值
}
如果值>当前最大值,则为else{
currentMax=值
}
}
返回值(当前最小值、当前最大值)
}
如果let bounds=minAndmax(数组:[8,-6,2,109,3,71]){
打印(边界)
}
您不能在swift中返回Nil值,请在方法中更改您的返回类型字符串。这可能有助于您显示函数的更多代码,即其返回类型。@Anbu.Karthik当返回类型为可选时,您可以在swift中返回Nil(可选类型实现NilLiteralConvertible)。问题是该方法的返回类型是字符串。如果他希望能够返回nil,那么返回类型应该是字符串?回答得很好。谢谢!非常感谢。
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)
}