For some reason I can't get optionals working in Swift. They seem to always be nil
. Either there's a bug somewhere, or I don't understand how optionals work. Here's what I'm doing:
First, I open up a Swift REPL: /Applications/Xcode6-Beta2.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift
Here's what I enter in the REPL (combined with return values):
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"
never gets printed, because let actualInt = perhapsInt
evaluates to false, because the line perhapsInt = 1
is doing absolutely nothing, so perphapsInt
retains its value of nil
.
The same occurs if I set perhapsInt
to a value during initialization:
1> var perhapsInt: Int? = 5
perhapsInt: Int? = 5
2> perhapsInt
$R1: Int? = nil
Any ideas?
This looks like a bug in the Swift REPL. You should file a Radar.
This snippet works just fine for me inside an Xcode playground:
var perhapsInt: Int? // nil
perhapsInt = 1 // {Some 1}
if let actualInt = perhapsInt {
actualInt // 1
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments