Swift 4数组映射无字符串

时间:2018-12-27 09:59:09

标签: arrays swift

所以我有这个简单的代码,并且数据类型比较快,想从中映射这个数组

 ["a", "b", nil, "c", "d", nil]

 ["a", "b", "z", "c", "d", "z"]

所以,这是我当前的代码

import Foundation

let array1 = ["a", "b", nil, "c", "d", nil]
let newArray = array1.map { (currentIndex: Any) -> String in
    if currentIndex == nil  {
        return "z"
    }
    return currentIndex as! String
}
print(newArray)

如果您尝试解决该代码,我将不胜感激。谢谢。

2 个答案:

答案 0 :(得分:10)

如果您将currentIndex声明为Any,则无法再将其与nil进行比较。您的情况下正确的类型应为String?

let newArray = array1.map { (currentIndex: String?) -> String in
    if currentIndex == nil  {
        return "z"
    }
    return currentIndex!
}

但是,编译器可以从上下文中自动推断出这一点:

let newArray = array1.map { currentIndex -> String in
    if currentIndex == nil  {
        return "z"
    }
    return currentIndex!
}

最好使用nil-coalescing运算符??,并避免强制展开:

let newArray = array1.map { currentIndex in
    currentIndex ?? "z"
}

或更短:

let newArray = array1.map { $0 ?? "z"  }

答案 1 :(得分:0)

您的代码绝对正确,但问题是您需要在map语句中传递可选参数,如下所示,并且对您的代码进行宾果游戏完全可以正常工作。

let array1 = ["a", "b", nil, "c", "d", nil]
let newArray = array1.map { (currentIndex: Any?) -> String in
    if currentIndex == nil  {
        return "z"
    }
    return currentIndex as! String
}
print(newArray)