如果我宣布String这样:var date = String()
我想检查天气是否与我nil String一样尝试:
if date != nil{
println("It's not nil")
}
Run Code Online (Sandbox Code Playgroud)
但我得到一个错误: Can not invoke '!=' with an argument list of type '(@lvalue String, NilLiteralConvertible)'
之后我试试这个:
if let date1 = date{
println("It's not nil")
}
Run Code Online (Sandbox Code Playgroud)
但仍然得到如下错误: Bound value in a conditional binding must be of Optional type
所以我的问题是,如果我以这种方式声明,我怎么能检查String不是?nil
jrt*_*ton 26
字符串不能为零.这就是Swift中这种打字的重点.
如果您希望它可能为nil,请将其声明为可选:
var date : String?
Run Code Online (Sandbox Code Playgroud)
如果你想检查一个字符串是空的(不要这样做,那就是可以解决的选项问题)然后:
if date.isEmpty
Run Code Online (Sandbox Code Playgroud)
但你真的应该使用选项.
你可以尝试这个......
var date : String!
...
if let dateExists = date {
// Use the existing value from dateExists inside here.
}
Run Code Online (Sandbox Code Playgroud)
快乐的编码!!!
| 归档时间: |
|
| 查看次数: |
30357 次 |
| 最近记录: |