19

私はプロトコルを定義しています:

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 以外のプロトコルを使用した条件付きバインディングでこの機能を実現するにはどうすればよいですか?

4

5 に答える 5

33

キャストを Usable にすることでコンパイルできますか? Usable の代わりに、次のようにします。

// Check whether or not a class is useable
if let usableThing = thing as Usable? { // error here
    usableThing.use()
}
else {
    println("can't use that")
}
于 2014-06-08T21:39:49.587 に答える
1

Swift doc に記載されているように、isオペレーターは仕事に必要な人です。

is 演算子は、式が指定された型であるかどうかを実行時にチェックします。その場合は true を返します。それ以外の場合は false を返します。

チェックは、コンパイル時に true または false であることがわかってはなりません。

したがって、通常は次のテストが必要になります。

if thing is Usable { 
    usableThing.use()
} else {
    println("can't use that")
}

ただし、ドキュメントで指定されているように、Swift はコンパイル時に式が常に true であることを検出し、開発者を支援するためにエラーを宣言できます。

于 2014-06-08T23:09:09.137 に答える
1

これは遊び場で私のために働きます

protocol Usable {
    func use()
}

class Thing: Usable {
    func use () {
        println ("you use the thing")
    }
}

let thing = Thing()
let testThing : AnyObject = thing as AnyObject

if let otherThing = testThing as? Thing {
    otherThing.use()
} else {
    println("can't use that")
}
于 2014-06-17T09:20:26.847 に答える
0

最初のベータ版の Playgrounds では、swift プロトコルは機能しません。代わりに、実際のプロジェクトを構築してみてください。

于 2014-06-09T11:18:15.333 に答える