Swift函数返回两种不同的类型 [英] Swift function returning two different types
本文介绍了Swift函数返回两种不同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个可以根据输入的参数返回String
或Int
的函数,例如:
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
}
}
推荐答案
使用枚举
您可以使用带有关联值的枚举来实现所需的行为.它们很像是C联合的更好版本.
Use an Enumeration
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
必须通过打开其类型并做出相应的响应来有条件地使用:
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)
}
这篇关于Swift函数返回两种不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文