swift - 给定一个 [Int] 类型的函数参数;可以限制它不为空吗?

标签 swift

请考虑以下事项:

func example(array: [Int]) {
    guard array.count > 0 else { return }

    // Do something
}

最好通过函数签名来宣布限制。是否可以限制参数?相当于:

func example(array: [Int] where array.count > 0) {
    // Do something
}

更进一步:让数组成为可选的:

func example(array: [Int]?) {
    guard array == nil || array!.count > 0 else { return }

    // Do something
}

func example(array: [Int]? where array.count > 0) {
    // Do something
}

最佳答案

不,您不能有条件参数。你能做的最好的就是你在第二个选项中有一个可选的,并且在你调用函数之前(或者可能在函数中)检查它是否为零。

关于swift - 给定一个 [Int] 类型的函数参数;可以限制它不为空吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40323966/

相关文章:

Swift:如何使用时区缩写解析日期和时间字符串?

ios - 上传图片到服务器时出现绿线

Swift:通用协议(protocol)

swift - 我想使用 SnapKit 将顶部 UIView 放置在 UITableView 之上

ios - Swift iOS -UrlSession 移动非常慢。有没有办法同时执行多个任务?

swift - 无法使用覆盖 init 方法调用类

swift - 使用 alamofire 排队

swift - 画外音 : can I adapt different voices tones in swift?

ios - Swift 中没有像 Sqlite 这样的模块

ios - 如何在没有 CaptiveNetwork 弃用框架的情况下在 Swift 2.0 中获取 ssid?