Reputation: 359
if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(mathematicalSymbol)
}
The code above introduces the error below;
Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?
As can be seen in this screen shot;
sender.currentTitle
is an optional.
Here is an excerpt from Apple's "The Swift Programming Language (Swift 2.2)" with its example code just below it;
If the optional value is
nil
, the conditional isfalse
and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant afterlet
, which makes the unwrapped value available inside the block of code.
Here is the sample code for that excerpt;
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello, \(name)"
}
So for these reasons, I'm thinking that either I'm missing something or that I'm hitting a bug.
I've also tried something similar on a Playground, and didn't get a similar error;
Here is my Swift version;
Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.31)
Target: x86_64-apple-macosx10.9
Upvotes: 2
Views: 108
Reputation: 437422
If you look at currentTitle
, you'll see it is likely inferred to be String??
. For example, go to currentTitle
in Xcode and hit the esc key to see code completion options, and you'll see what type it thinks it is:
I suspect you have this in a method defining sender
as AnyObject
, such as:
@IBAction func didTapButton(sender: AnyObject) {
if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(mathematicalSymbol)
}
}
But if you explicitly tell it what type sender
is, you can avoid this error, namely either:
@IBAction func didTapButton(sender: UIButton) {
if let mathematicalSymbol = sender.currentTitle {
brain.performOperation(mathematicalSymbol)
}
}
Or
@IBAction func didTapButton(sender: AnyObject) {
if let button = sender as? UIButton, let mathematicalSymbol = button.currentTitle {
brain.performOperation(mathematicalSymbol)
}
}
Upvotes: 3