首页 > 解决方案 > 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 }

标签: swift

解决方案


那是因为 postscriptNames 也是类型 [Any] 吗?

是的。和postscriptNamestype一样[Any],你需要向下转换$0.name为 String

lengths = postscriptNames.compactMap { ($0.name as? String).count }

将其向下转换为 String 以获取计数。


推荐阅读