0

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

UserNil
  • 129
  • 9
  • You seem to have a big misunderstanding here. If you want the compiler to know about `myArray1`, then just declare `buildMyArray` to return `myArray1`. The whole purpose of opaque types is to *hide* the specific type that is returned, but at the same time ensure that the function does return a specific, concrete type (as opposed to an existential like `any Editable`). – Sweeper Aug 09 '23 at 03:46

0 Answers0