swift - Swift 中的可选赋值不起作用?

标签 swift

出于某种原因,我无法在 Swift 中使用选项。它们似乎总是nil。要么某个地方有错误,要么我不明白选项是如何工作的。这就是我正在做的事情:

首先,我打开一个 Swift REPL:/Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift

这是我在 REPL 中输入的内容(与返回值结合):

1> var perhapsInt: Int?
perhapsInt: Int? = nil
2> perhapsInt = 1
3> if let actualInt = perhapsInt {
4.     println("here")
5. }
6> perhapsInt
$R2: Int? = nil

"here" 永远不会被打印,因为 let effectiveInt = 也许Int 的计算结果为 false,因为 perhapsInt = 1 行绝对没有执行任何操作,因此 perphapsInt 保留其值 nil

如果我在初始化期间将 perhapsInt 设置为一个值,也会发生同样的情况:

1> var perhapsInt: Int? = 5
perhapsInt: Int? = 5
2> perhapsInt
$R1: Int? = nil

有什么想法吗?

最佳答案

这看起来像是 Swift REPL 中的一个错误。你应该file a Radar .

这段代码在 Xcode Playground 中对我来说效果很好:

var perhapsInt: Int?                  // nil
perhapsInt = 1                        // {Some 1}

if let actualInt = perhapsInt {
    actualInt                         // 1
}

关于swift - Swift 中的可选赋值不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24391990/

相关文章:

ios - 无论如何,是否可以使用 React Native 向 TabBarIOS 呈现 native Controller ?

ios - 在 NSIndexPath 上意外发现 nil 运行时错误

ios - 为什么我在 Swift 中收到多个 UILocalNotifications?

ios - SWIFT:在 performSegueWithIdentifier 之后未加载原型(prototype)单元格

ios - 如何从以编程方式创建的 UITableView 继续?

ios - 在 Simulator Swift 中运行时出现 CLLocationCooperative2D 错误

ios - 在字符串末尾添加一个字符后,会添加一个不需要的空格。我该如何删除这个?

objective-c - 如何调用接受 block 字典作为 Swift 参数的 Objective-C 函数?

ios - 快速在 UIView 子类中创建 subview

ios - 关于自定义全局UIButton的问题