iOS,在swift

时间:2015-11-06 05:16:12

标签: objective-c swift protocols

MyObjcClass的成员变量类型为UIView<FooProtocol>* myView

MySwiftClass扩展MyObjcClass并尝试使用myView

myView.doFoo()是swift中的错误,因为swift认为myViewUIView而非UIView<FooProtocol>

2 个答案:

答案 0 :(得分:0)

我不认为从UIView<FooProtocol>*到Swift有一个很好的直接映射。你最好的选择可能只是投出它然后打电话:

(myView as! FooProtocol).doFoo()

如果你可以控制objective-c类,那么将myView重新定义为FooProtocol可能更容易:

id<FooProtocol> myView;

或者,在基类中定义一个为您调用doFoo的方法:

-(void)doFoo {
    [myView doFoo];
}

在这种情况下,您可以使用swift中的基类方法:

self.doFoo()

答案 1 :(得分:-1)

protocol FooProtocol {
    func foo()
}
class BaseFoo {

}
class Foo: BaseFoo, FooProtocol {
    func foo() {
        print("job as required by FooProtocol")
    }
}

class MyClass {
    var myFoo: Foo = Foo()
    var myFoo2: BaseFoo = Foo()
    // I dont have an idea about the type, but i know it comforms to FooProtocol
    var myFoo3: protocol<FooProtocol> = Foo()
}

let myClass: MyClass = MyClass()
myClass.myFoo.foo()     // job as required by FooProtocol
//myClass.myFoo2.foo()  // error: value of type 'BaseFoo' has no member 'foo'
myClass.myFoo3.foo()    // job as required by FooProtocol