swift - Swift 5.1:如何在一种类型的集合上调用 map 并返回另一种不同类型的集合?
问题描述
我一直在玩 Swift 中的函数式编程。但是,我遇到了一个问题。
如果我在一种类型的集合上调用 map ,如何创建另一种类型的新集合?
var fontFamilyMembers = [[Any]]()
//...
let postscriptNames = fontFamilyMembers.map {
[
"name": $0[0] as! String,
"weight": $0[2] as! Int,
"traits": $0[3] as! UInt
]
}
// Error: Value of type 'Any?' has no member 'count'
lengths = postscriptNames.map { $0["name"].count }
我知道我需要转换$0["name"]
为字符串。当我已经在上面完成了它时,为什么我必须这样做?( "name": $0[0] as! String
)。那是因为postscriptNames
也是 type[[Any]]()
吗?
我试过这个:
// Error: Cannot convert value of type 'Int' to closure result type 'String'
fontPostscriptNames = postscriptNames.map { ($0["name"] as! String).count }.joined(separator: "\n")
......但我知道我很困惑。
如何让 map 返回每个的计数"name"
?
更新
我原来的问题仍然存在。但是,我可以通过使用结构而不是字典来完全避免这个问题,我认为字典在 Swift 中是首选。
let postscriptNames = fontFamilyMembers.map {
(
name: $0[0] as! String,
weight: $0[2] as! Int,
traits: $0[3] as! UInt
)
}
lengths = postscriptNames.map { $0.name.count }
解决方案
那是因为 postscriptNames 也是类型 [Any] 吗?
是的。和postscriptNames
type一样[Any]
,你需要向下转换$0.name
为 String
lengths = postscriptNames.compactMap { ($0.name as? String).count }
将其向下转换为 String 以获取计数。
推荐阅读
- c++ - 在链表中移动构造函数实现
- python-3.x - Tkinter - 我无法禁用按钮小部件
- azure - Microsoft Azure WebApp 在 S2 上扩展到 10 个实例
- ios - 故事板上的视图控制器和我通过代码定义的视图控制器有什么关系?
- python - 索引号从 0 开始的模数?
- android - 为什么获取游戏存档功能的存档图片大小的API会报错?
- android - 如何识别android数据绑定中的错误?[AGP 4.0 +]
- python-3.x - 熊猫细胞内 nparray 的 len
- c++ - opencv C++中的傅里叶变换和逆变换
- aws-cli - 使用 aws cli 是否可以找到在 ECS 实例中运行的任务是什么