Swift generics method in EXC_BAD_ACCESS

Viewed 99

I'm stuck about generics, and generic methods in swift.

Why this code that uses Swift generics method, gives EXC_BAD_ACCESS when invoking method1?

You can test it using Playground.

import UIKit
import Foundation

protocol SomeProtocol {
    func printMe()
}

class SomeClass : SomeProtocol {
    let value : String

    init(value: String) {
        self.value = value
    }
    func printMe() {
        print("\(value)")
    }
}

class BaseClass {
    func method1<T>(_ param: T) {
        print("passing into method 1 with param: \(param)")
        method2(param)
    }

    func method2<T>(_ param: T) {
    }
}

class ConcreteClass : BaseClass {

    override func method2<T>(_ param: T) where T : SomeProtocol {
        print("passing into method 2 with param: \(param.printMe())")
    }
}

let someClass = SomeClass(value: "Hi")

let obj = ConcreteClass()
obj.method1(someClass)
1 Answers

The fact that you've managed to override the method with where closure without a compilation error really looks like a bug. But there is a workaround for your use case:

class ConcreteClass : BaseClass {
    override func method2<T>(_ param: T) {
        print("Base param \(param)")
        if let printable = param as? SomeProtocol {
            printable.printMe()
        }else {
            super.method2(param)
        }
    }
}
Related