本文介绍了Swift:Nil与返回类型String不兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Swift中有这个代码:
I have this code in Swift:
guard let user = username else{
return nil
}
但我收到以下错误:
Nil is incompatible with return type String
你知道为什么或如何在这种情况下返回nil?
Any of you knows why or how I return nil in this case?
我真的很感谢你的帮助
推荐答案
你必须告诉编译器你要返回nil。那你怎么样?通过在对象后面指定'?'。例如,看一下这段代码:
you have to tell the compiler that you want to return nil. How do you that? by assigning '?' after your object. For instance take a look at this code:
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)
}
请注意,我必须告诉编译器我的对象朋友我正在返回的是一个可选的'朋友?',否则它会在我身上泄漏错误
Notice that i had to tell the compiler that my Object Friend that i'm returning is an optional 'Friend?' other wise it spill an error on me
这篇关于Swift:Nil与返回类型String不兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!