Search code examples
swifttype-mismatchmismatchopaque-types

Swift: returning a runtime random opaque type generates an error


I am learning opaque types now, still a bit confusing. I tried the following:

protocol Animal {
    func introduce()
}

struct Dog: Animal {
    func introduce() {
        print("Dog")
    }
}

struct Cat: Animal {
    func introduce() {
        print("Cat")
    }
}

func random() -> some Animal {
    let value = [true, false].randomElement()!
    return value ? Cat() : Dog()
}

And in the return line of random I am getting the following error

Result values in '? :' expression have mismatching types 'Cat' and 'Dog'

So, as far as I understand just like Generics the compiler needs to be able to decide at compile time what the concrete return type of the function is.

Am I right? If I am, isn't this message about confusing as both structs implement Animal? And if I'm wrong, what does this error message mean?

Thanks a lot

EDIT: I'm trying to understand, not to make it work :)


Solution

  • Consider this: What is the type of the expression value ? Cat() : Dog() It isn’t animal. And for a ternary you need one type but you have either a cat or a dog. Type inference isn’t going to figure out that you can erase those two different types back to some common type, even if it’s possible to do so