2016-08-01 10 views
2
if let mathematicalSymbol = sender.currentTitle { 
    brain.performOperation(mathematicalSymbol) 
} 

上記のコードでは、以下のエラーが発生しています。Swift 2.2のオプションのバインディングのバグ?

オプションの値 'String?'の値アンラップされていない。 '!'を使用することを意味しましたか?または '?'?

このスクリーンショットからわかるように、

enter image description here

sender.currentTitleオプションです。

Appleの「The Swift Programming Language (Swift 2.2)」の抜粋ですが、そのすぐ下のサンプルコードがあります。

任意の値がnilある場合、条件はfalseであり、括弧内のコード はスキップされます。そうでなければ、任意の値は、コードのブロック内 利用可能開封された値になりアンラップlet後に一定に割り当て 、です。

以下は、その抜粋のサンプルコードです。

var optionalName: String? = "John Appleseed" 
var greeting = "Hello!" 
if let name = optionalName { 
    greeting = "Hello, \(name)" 
} 

は、したがって、これらの理由から、私はどちらか、私はが何かを見つからないか、私はバグを打つだということだと考えています。

私はプレイグラウンドでも同様のことを試しましたが、同様のエラーは発生しませんでした。ここで

enter image description here

私スウィフトバージョンです。

Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.31) 
Target: x86_64-apple-macosx10.9 
+0

おそらく関連:[の奇妙な行動スウィフトのANYOBJECT](http://stackoverflow.com/questions/33388830/the-strange-behaviour-of-swifts-anyobject)。 –

答えて

2

あなたはcurrentTitleを見れば、あなたはおそらくString??と推定されて表示されます。たとえば、XcodeでcurrentTitleに移動し、コード補完のオプションを表示するESCキーを押すと、あなたはそれがあると考えてどのような種類がわかります:

enter image description here

私はあなたがこの方法でこれを持っている疑いがありますなど、AnyObjectとしてsenderを定義する:

@IBAction func didTapButton(sender: AnyObject) { 
    if let mathematicalSymbol = sender.currentTitle { 
     brain.performOperation(mathematicalSymbol) 
    } 
} 

しかし、あなたが明示的にどのようなタイプsenderであることを教えている場合、あなたはつまりどちらか、このエラーを回避することができます

@IBAction func didTapButton(sender: UIButton) { 
    if let mathematicalSymbol = sender.currentTitle { 
     brain.performOperation(mathematicalSymbol) 
    } 
} 

それとも

@IBAction func didTapButton(sender: AnyObject) { 
    if let button = sender as? UIButton, let mathematicalSymbol = button.currentTitle { 
     brain.performOperation(mathematicalSymbol) 
    } 
} 
+0

'もしlet mathematicalSymbol =(送信者は?UIButton)?currentTitle {'も動作します。 – vacawama

+0

うん、それも動作します! – Rob

+1

私は、Xcodeが 'sender'型のために' AnyObject'にデフォルト設定されているのは面倒です。 'AnyObject'は誰も送信者にとって欲しがるものであることはめったにないので、本当に必要な場合にはIMHOを選択する必要があります。 – vacawama

関連する問題