Calling methods on a Swift Opaque return

22 Views Asked by At

Trying to wrap my head around the use of Opaque and typealias. My understanding is that the compiler at compile time will ensure the concrete definition of the opaque return is available so the caller can get that instance and access the specific methods on that instace.

protocol Editable {
    associatedtype MyType
    
    var data: [MyType] {get set}
    
    func add(_ item: MyType)
}

struct myArray1: Editable {
    typealias MyType = String

    var data = [String]()
    
    func add(_ item: String) {
        print("myArray1 will process string \(item)")
    }
    
    func hello() {
        print("This is myArray1")
    }
}

struct myArray2: Editable {
    typealias MyType = Int
    
    var data = [Int]()
    
    func add(_ item: Int) {
        print("myArray2 will process Int \(item)")
    }
    
    func hello() {
        print("This is myArray2")
    }
}

func buildMyArray() -> some Editable {
    return myArray1()
}


let testData = buildMyArray()

testData.add("") // Why the compiler does not see the parameter as string? how would I call this method?

testData.hello() // Why I cannot access the hello method from the concrete struct, only way is to add it to the interface

0

There are 0 best solutions below