-8

When I get the value from a Text Field and cast it to an integer, I get log output that says Optional(5) if I inputted 5, or Optional(1234) if I inputted 1234.

What does Optional() mean?

Here is the code to get and cast the value:

@IBOutlet weak var myInput: UITextField!

// When a button is clicked, I log the value in the UI text field.
@IBAction func someButton(sender: AnyObject) {
  println(self.myInput.text.toInt())        
}
Don P
  • 60,113
  • 114
  • 300
  • 432
  • http://stackoverflow.com/questions/25846561/swift-printing-optional-variable – 67cherries Dec 13 '14 at 00:55
  • 4
    It means it's an Optional. If you don't know what an Optional is, how can you use Swift at all? I mean, this is on the _first page_ of the Swift manual, for heaven's sake. https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_496 – matt Dec 13 '14 at 00:57
  • 4
    This question appears to be off-topic because it is about using Swift without even trying to learn Swift. – matt Dec 13 '14 at 01:00
  • There are so many good close reasons for this question. http://stackoverflow.com/q/24003642/901059 It's also a duplicate. – N_A Dec 13 '14 at 01:02
  • Ok guys, bad question, downvoted to hell, I got it :) If I could close or delete it I would. It was my first day doing Swift, and I didn't realize this was in the official docs. – Don P Dec 14 '14 at 05:30

1 Answers1

0

Optional means the value is Optional type. It can be either nil or a value. When working with cocoa api most of the method parameters are optional type. To get actual value from optional value you either use if-let binding or force it to unwrap it with ! operator. Suppose ve have a value of a optional type of Int. Let's define it first.

let a: Int? = 5

The ? denotes it is an optional value. If you print this a it will write Optional(5). Let's get the actual value from it.

if let actualA = a {
    println(actualA)
}

Now if a is not nil then the code inside if-let statement will be executed and it will print 5 on the console.

Optional types are for dealing with nil values in swift. They provide extra safety when working parameters and variables. If a value is not optional than it can never be nil. So we can safely do our work without worrying about nil values.

mustafa
  • 15,254
  • 10
  • 48
  • 57