I need a function that can return either a String
or an Int
depending on the parameters entered eg:
func getValue (type: String) -> (String || Int) { //this line is obviously wrong
if type == "type1" {
return "exampleString"
}
else if type == "type2"
return 56
}
}
You can use an enumeration with associated values to achieve the behaviour you're looking for. They're much like a nicer version of C's unions.
enum Foo { //TODO: Give me an appropriate name.
case type1(String)
case type2(Int)
static func getValue(type: String) -> Foo {
switch (type) {
case "type1": return type1("exampleString")
case "type2": return type2(56)
default: fatalError("Invalid \"type\"");
}
}
}
let x = Foo.getValue(type: "type1")
x
must be consumed conditionally, by switching on its type and responding accordingly:
switch x {
case .type1(let string): funcThatExpectsString(string)
case .type2(let int): funcThatExpectsInt(int)
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments