如何在Swift中将variadic(省略号)参数指定为可选参数?

时间:2021-09-29 10:56:30

Is it possible to have a variadic parameter be optional in Swift? I tried the two ways that made sense and neither compile:

在Swift中是否可以选择变量参数?我尝试了两种有意义且无法编译的方法:

func myFunc(queryFormat: String?...) {

}

or

要么

func myFunc(queryFormat: String...?) {

}

Note: The 1st implementation technically compiles but if you try to unwrap it:

注意:第一个实现在技术上编译,但如果您尝试打开它:

if let queryFormatUnwrapped = queryFormat {
...
}

You get an error Bound value in a conditional binding must be of Optional Type which indicates to me its treating it as an Array of optional Strings not an optional Array of Strings (which is kind of silly).

你得到一个错误条件绑定中的绑定值必须是Optional Type,它向我表明它将它视为一个可选字符串数组而不是一个可选的字符串数组(这有点愚蠢)。

1 个解决方案

#1


13  

It's not possible to have a an optional variadic parameter. The function will always receive an array for the variadic parameter.

不可能有一个可选的variadic参数。该函数将始终接收可变参数的数组。

However, the array can be empty, or the values in the array can be nil.

但是,数组可以为空,或者数组中的值可以为nil。

I threw some sample code together, hope it helps communicate what I'm trying to say.

我把一些示例代码放在一起,希望它能帮助传达我想说的内容。

func vardicPrint(strings: String...) {
    if strings.isEmpty {
        print("EMPTY")
    } else {
        for string in strings {
            print(string)
        }
    }
}

func optionalPrint(maybeStrings: String?...) {
    if maybeStrings.isEmpty {
        print("EMPTY")
    } else {
        for string in maybeStrings {
            if let string = string {
                print(string)
            } else {
                print("nil")
            }

        }
    }
}

vardicPrint("Hello", "World", "!")
vardicPrint()


var nilString: String?
optionalPrint("Goodbye", nilString, "World", "!")

/* OUTPUT:
Hello
World
!
EMPTY

Goodbye
nil
World
!
*/

#1


13  

It's not possible to have a an optional variadic parameter. The function will always receive an array for the variadic parameter.

不可能有一个可选的variadic参数。该函数将始终接收可变参数的数组。

However, the array can be empty, or the values in the array can be nil.

但是,数组可以为空,或者数组中的值可以为nil。

I threw some sample code together, hope it helps communicate what I'm trying to say.

我把一些示例代码放在一起,希望它能帮助传达我想说的内容。

func vardicPrint(strings: String...) {
    if strings.isEmpty {
        print("EMPTY")
    } else {
        for string in strings {
            print(string)
        }
    }
}

func optionalPrint(maybeStrings: String?...) {
    if maybeStrings.isEmpty {
        print("EMPTY")
    } else {
        for string in maybeStrings {
            if let string = string {
                print(string)
            } else {
                print("nil")
            }

        }
    }
}

vardicPrint("Hello", "World", "!")
vardicPrint()


var nilString: String?
optionalPrint("Goodbye", nilString, "World", "!")

/* OUTPUT:
Hello
World
!
EMPTY

Goodbye
nil
World
!
*/