首页 > 解决方案 > Xcode 显示不需要的语法错误

问题描述

我有一个带有值的枚举:

enum Types {
  case A
  case B
  case C
  case D
}

var tableViewDataSource: [Types] = [.A, .B, .C, .D]

我想实现以下条件:

let pickerSelectingFields: [Types] = [.A, .B, .C, .D]
    let indexes = pickerSelectingFields.map { tableViewDataSource.firstIndex(of: $0) }

    if indexes.contains(textField.tag) {
    // Working
    }

当我尝试将所有内容放在一行中时,如下所示显示错误:

闭包中不包含匿名闭包参数

代码如下:

if ([.A, .B, .C, .D] as? [Types]).map { tableViewDataSource.firstIndex(of: $0) }
                                 .contains(textField.tag)

我在这里做错了什么?

标签: iosswiftenums

解决方案


if ([.A, .B, .C, .D] as? [Types]).map { tableViewDataSource.firstIndex(of: $0) }
                             .contains(textField.tag)

我在这里做错了什么?

有两个问题。

首先,您使用as?而不是as. 当您使用条件强制转换as?时,结果是[Types]?:一个可选 [Types]的。然后 Swift 使用可选版本,map而你主要是朝着错误的方向前进。

您需要使用as [Types],因为您只是告诉 Swift 解释[.A, .B, .C, .D][Types].

第二个问题是,由于您在一行中执行此操作,因此您需要一些额外的括号()围绕闭包 for,map因为 Swift 不喜欢{if. 在不澄清括号的情况下,它会将属于 for 闭包的{一个map解释为.if

所以:

if ([.A, .B, .C, .D] as [Types]).map({ tableViewDataSource.firstIndex(of: $0) }).contains(textField.tag) {
    // do something
}

将工作。

你也可以只显式地输入数组的一个条目,Swift 会将整个数组解释为[Types]

if [Types.A, .B, .C, .D].map({ tableViewDataSource.firstIndex(of: $0) }).contains(textField.tag) {
    // do something
}

笔记:

常见的 Swift 约定以大写class字母开头、、structenum类型名称,并以小写字母开头变量、方法和枚举值。

所以你enum可以写成:

enum Types {
    case a, b, c, d
}

推荐阅读