ios - 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)
我在这里做错了什么?
解决方案
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
字母开头、、struct
和enum
类型名称,并以小写字母开头变量、方法和枚举值。
所以你enum
可以写成:
enum Types {
case a, b, c, d
}
推荐阅读
- javascript - node-cmd 打印 Microsoft Word 文档
- java - 如何使用 Ant build 和 Java 11 编译 JSP?
- ssh - 无法在 sftp kubernetes 部署中使用持久主机密钥
- azure - 如何让本地 AD 用户使用 Azure AD 的主要自定义域作为云服务的 UPN 后缀
- microsoft-graph-api - 用于创建共享邮箱的 Microsoft Graph API
- java - 休息控制器触发 AWS lambda
- java - 如何为diffie hellman算法生成curve25519密钥对?
- spring-boot - 关于 javamail 属性的说明
- c++ - 使用 std::istream::operator>> 处理无符号类型,我如何区分从下溢中提取失败?
- reactjs - React TypeScript:停止状态进行多个 api 调用