I'm new to swift, having some experiences in other language like c, java, C#, python.
I have problem to understand the swift keyword some and any.
I do read the docs here Documentation
A function or method that returns an opaque type hides its return value’s type information. Instead of providing a concrete type as the function’s return type, the return value is described in terms of the protocols it supports. Opaque types preserve type identity — the compiler has access to the type information, but clients of the module don’t.
But I still can not make the codes to work like below:
protocol Shape{}
struct Squre: Shape {}
struct Circle: Shape {}
/* normally I use protocol this way, it's just interface for other languages
*/
func creatShape(_ seed:Int) -> Shape {
if seed % 2 == 0 {return Circle()}
else {return Squre()}
}
/*
goes alright, I don't know why need keyword "any" for, why not just use the first one
*/
func creatAnyShape(_ seed:Int) -> any Shape {
if seed % 2 == 0 {return Circle()}
else {return Squre()}
}
/*oops,the some keywords goes wrong, how can we make it work then?
error mesages here:
function declares an opaque return type,
but the return statements in its body do not have matching underlying types
*/
func creatSomeShape(_ seed:Int) -> some Shape{
if seed % 2 == 0 {return Circle()}
else {return Squre()}
}
let seed=Int.random(in: 1..<11)
var shape1 = creatAnyShape(seed)
print(seed,shape1)