简体   繁体   English

Swift中Optional(“ nil”)的含义是什么?

[英]What's the meaning of Optional(“nil”) in Swift?

Here is my code. 这是我的代码。 If defaults did not ever save the lat, lng, then give it a lat lng. 如果默认值从未保存经度,请给它一个经度。

The problem is error: 问题是错误:

fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:解开Optional值时意外发现nil

when using self.lat and self.lng after the code below. 在以下代码后使用self.latself.lng时。 Every time console print out is 每次控制台打印输出为

the saved gps is Optional("nil") 保存的gps是Optional(“ nil”)

What's the meaning for Optional("nil") and the difference from Optional(nil) ? 什么是对的含义Optional("nil")并从差Optional(nil)

I am using Xcode 7.1 and Swift 2. 我正在使用Xcode 7.1和Swift 2。

var lat : String = ""
var lng : String = ""

let defaults = NSUserDefaults.standardUserDefaults()
if  defaults.stringForKey("lat") != nil  {
    self.lat = defaults.stringForKey("lat")!
    self.lng = defaults.stringForKey("lng")!
    print ("the saved gps is \(defaults.stringForKey("lat"))")
} else {
    self.lat = "34.7009333"
    self.lng = "135.4942047"
    print ("the init gps is  \(self.lat) , \(self.lng)")
}

it show the actual value... 它显示实际值...

let digit = sender.currentTitle!

suppose your sender value is 10 then output is 10. 假设您的发件人值为10,然后输出为10。

suppose your sender value is nil then app carsh. 假设您的发件人值为零, 则为app carsh。

it show the optional value 显示可选值

   let digit = sender.currentTitle

suppose your sender value is 10 then output is optional("10"). 假设您的发件人值为10,那么输出是可选的(“ 10”)。

suppose your sender value is nil then app is not carsh. 假设您的发件人值为零,那么应用程序不是carsh。

& display value like this optional("nil") &显示值,像这样可选(“ nil”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM