Swift function returns two different types

I need a function that can return either String, or Intdepending on the entered parameters, for example:

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

Use enumeration

You can use an enumeration with related values ​​to achieve the desired behavior. They are very similar to the more convenient version of C 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 it is necessary to use conditionally, switching its type and reacting accordingly:

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

I would suggest using a tuple with additional values, and then create code to deploy them.

Any , , String Int, , .

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
} 
+1

Source: https://habr.com/ru/post/1657702/


All Articles