私はプロトコルを定義しています:
protocol Usable {
func use()
}
およびそのプロトコルに準拠するクラス
class Thing: Usable {
func use () {
println ("you use the thing")
}
}
Thing クラスが Usable プロトコルに準拠しているかどうかをプログラムでテストしたいと考えています。
let thing = Thing()
// Check whether or not a class is useable
if let usableThing = thing as Usable { // error here
usableThing.use()
}
else {
println("can't use that")
}
しかし、私はエラーが発生します
Bound value in a conditional binding must be of Optional Type
私が試したら
let thing:Thing? = Thing()
エラーが発生します
Cannot downcast from 'Thing?' to non-@objc protocol type 'Usable'
@objc
次に、プロトコルに追加してエラーを取得します
Forced downcast in conditional binding produces non-optional type 'Usable'
その時点で?
の後に追加するas
と、最終的にエラーが修正されます。
「Advanced Swift」2014 WWDC ビデオと同じように、@objc 以外のプロトコルを使用した条件付きバインディングでこの機能を実現するにはどうすればよいですか?