This works:
func makeArray(shouldMakeInt: Bool) -> Array<Any>
{
if shouldMakeInt
{
return Array<Int>()
}
else
{
return Array<String>()
}
}This doesn't:
func make(shouldMakeInt: Bool) -> A<Any>
{
if shouldMakeInt
{
return A<Int>()
}
else
{
return A<String>()
}
}("A<Int> is not convertible to A<Any>")
I'm trying to write a parsing function that takes a string and depending on the string contents, it returns either struct A<Int> or struct A<Bool>.
(Specifically, I'm tryint to unarchive a generic struct I've previously archived into a string).
Few questions:
(1) How can I make the above function "make" work with my struct A? It works with the built-in Array.
(2) What's the best way to approach this? I cannot make the function "make" generic, because I do not know the concrete type of the generic A<T> struct before the argument of the function is analyzed at runtime.
(3) What is the best approach for archiving and unarchiving Swift structs, in particular, generic structs?
It seems you cannot add Array like behaviors to your own struct.
You can define a function which returns Any.
func make(shouldMakeInt: Bool) -> Any
{
if shouldMakeInt
{
return A<Int>()
}
else
{
return A<String>()
}
}Or you can defined a wrapping enum and use it as return type.
enum Result {
case INT(A<Int>)
case STR(A<String>)
}
func make(shouldMakeInt: Bool) -> Result
{
if shouldMakeInt
{
return .INT(A())
}
else
{
return .STR(A())
}
}