I would like to create some functions in my Swift project that can accept either an object or a closure that returns this type of object. Of course, I could define the same function with multiple signatures in each place, but this is verbose. I would also like to be able to create types of safe lists of these objects / objects-returns-closures, but I cannot do this without some general type describing both things.
This is what I would like to do.
typealias StringClosure = () -> String
protocol Stringable {
func toStringClosure() -> StringClosure
}
extension String : Stringable {
func toStringClosure() -> StringClosure {
return { return self }
}
}
extension StringClosure : Stringable {
func toStringClosure() -> StringClosure {
return self
}
}
func printStringable(a : Stringable) {
print(a.toStringClosure()())
}
var stringableList : Stringable[] = ["cat", {return "dog"}, "gecko"]
for stringable in StringableList {
printStringable(stringable)
}
But this does not work, because I cannot actually expand my type StringClosurefor implementation Stringable. I could make a stringableListlist of types Any, but not a safe type.
Listing Solution
, , , , , . :
enum StringableEnum {
case Str(String)
case Fun(StringClosure)
}
func printStringableEnum(a : StringableEnum) {
switch (a) {
case let .Str(value):
print(value)
case let .Fun(value):
print(value())
}
}
var enumList : StringableEnum[] = [.Str("cat"), .Fun({return "dog"}), .Str("gecko")]
for element in enumList {
printStringableEnum(element)
}
, , API , , printStringableEnum, .Str .Fun. API!
, , - ?