KD J
KD J

Reputation: 21

Calling a protocol method results in a crash

I use protocol to call a func and then I get a crash . I know how to fix that ,but I want to exact know, why it can't work ,and why that can work . I think the problem may be is method dispath problem.

protocol Testable where Self : UIView{
    func update()
}

class JKD : UIView,Testable{
    func update() {
        print("JKD")
    }
}

func test(a : Testable){
    a.update()
}

let j2 : JKD = JKD.init(frame: CGRect.zero)
test(a: j2) // it will crash 

And this crash have mush of way to fix , like this :

@objc protocol Testable where Self : UIView{
    func update()
}

or this :

protocol Testable{
    func update()
}

and if the func use Generic,it also can fix the crash

func test<T : Testable>(a : T) {
    a.update()
}

or if the class in extension inherit the protocol,it can fix the crash too.

class JKD : UIView{}
extension JKD : Testable{
    func update() {
        print("JKD")
    }
}

so , in this case I want to know, why just the first way will crash .

Upvotes: 2

Views: 185

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

From the Swift 5 release notes,

Protocols can now constrain their conforming types to those that subclass a given class. Two equivalent forms are supported:

protocol MyView: UIView { /*...*/ }
protocol MyView where Self: UIView { /*...*/ } 

Swift 4.2 accepted the second form, but it wasn’t fully implemented and could sometimes crash at compile time or runtime. (SR-5581) (38077232)

Seems like they have fixed existing issues in Swift 5. It works fine on Xcode 10.2 beta 4.

Upvotes: 1

Related Questions