Swift函数返回两种不同的类型

Mat*_*eth 8 function ios swift

我需要一个可以返回a String或者Int取决于输入参数的函数,例如:

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

Ale*_*ica 21

使用枚举

您可以使用具有关联值的枚举来实现您正在寻找的行为.它们就像是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")
Run Code Online (Sandbox Code Playgroud)

x 必须有条件地消费,通过打开它的类型并做出相应的响应:

switch x {
    case .type1(let string): funcThatExpectsString(string)
    case .type2(let int): funcThatExpectsInt(int)
}
Run Code Online (Sandbox Code Playgroud)