简体   繁体   中英

Inconsistent Return Types for Functions in Swift

I have a function in Python with inconsistent return types:

def my_function(input):
  if(condition1): 
    return true
  if(condition2):
    return input

Now, I want to convert it to swift. Does Swift support inconsistent return types for functions? If yes, how?

If swift can do it, then I won't have to go through changing the logic of my Python code to convert it to Swift.

Since Swift is strongly typed, you cannot define a function that returns different types (unless you return a protocol, for example "Any", in which case anything that implements that protocol is a valid return type, but I don't know if that's what you want). What you can do is define an enum with your two types and return the enum. For example:

enum ReturnType {
    case Error
    case Input(String)
}

func myFunction(input: String) -> ReturnType {
    if input.isEmpty {
        return .Error
    }

    return .Input(input)
}

switch myFunction("Hello") {
    case .Error:
        println("Error!")

    case .Input(let input):
        println("Input \(input)!")
}

// Output: "Input Hello!"

If you say that the function returns something it has to return something, but this can be anything:

func my_function( input: Any ) -> Any? {
    if( 0 == 1 ) {
        return true
    }
    if( 1 == 1 ) {
        return input
    }
    return nil
}

The questionmark says that the function can also return nil (an optional). If you know it will always return something you can write it like this but "something" has to be something valid:

func my_function( input: Any ) -> Any {
    if( 0 == 1 ) {
        return true
    }
    if( 1 == 1 ) {
        return input
    }
    return 5
}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM