2016-10-14 65 views
4

我需要一个可以返回取决于参数StringInt进入的功能,例如:斯威夫特函数返回两种不同类型的

func getValue (type: String) -> (String || Int) { //this line is obviously wrong 
    if type == "type1" { 
     return "exampleString" 
    } 
    else if type == "type2" 
     return 56 
    } 
} 
+0

在什么情况下是否有意义这样做呢? – Alexander

+0

使用'任何'如果你必须声明该功能 – duan

+0

* facepalm *当然,谢谢!没想到这个 –

回答

17

使用枚举

您可以使用枚举关联值来实现您正在寻找的行为。它们很像C工会的更好版本。

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必须有条件地吞噬,其类型切换,并相应地作出反应:

switch x { 
    case .type1(let string): funcThatExpectsString(string) 
    case .type2(let int): funcThatExpectsInt(int) 
} 
1

我建议使用带有可选的值的元组,然后创建代码相应地打开它们。

类型Any应该尽量少用,你知道这是无论是StringInt意味着元组可能是你使用的情况下,最合适的解决方案的事实。

func someFuction(type: String) -> (String?, Int?) { 
    //Do stuff here 
} 

展开可选开关例如:

let sometuple: (string: String?, int: Int?) = ("Hi", 10) 

switch sometuple { 
    case let (.some(s), .some(i)): 
     print("String: \(s), Int: \(i)") 

    case let (.some(s), nil): 
     print(s) 

    case let (nil, .some(i)): 
     print(i) 

    case (nil, nil): 
     print("Nothing") 

} 
//prints "String: Hi, Int: 10" 

这部作品的原因是因为Optional是一个枚举:

enum Optional<T> { 
    case some(x:T) 
    case none 
} 
+0

是的,如果你能告诉我如何解开它将会很好 –

+2

这不适合使用元组/选项。这是浪费的记忆方式,对于许多类型来说都不能很好地扩展,打开包装很痛苦。 – Alexander

+0

@MattWyeth添加了我的开关可选的展开示例 – hooliooo