简体   繁体   English

Swift中函数的返回类型不一致

[英]Inconsistent Return Types for Functions in Swift

I have a function in Python with inconsistent return types: 我在Python中有一个函数,其返回类型不一致:

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? Swift是否支持不一致的函数返回类型? 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. 如果swift可以做到,那么我就不必通过更改Python代码的逻辑即可将其转换为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). 由于Swift是强类型的,因此您无法定义返回不同类型的函数(除非您返回协议,例如“ Any”,在这种情况下,实现该协议的任何东西都是有效的返回类型,但是我不知道这是否是你想要什么)。 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). 问号表示该函数还可以返回nil(可选)。 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. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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