Swift将空字符串映射为nil

时间:2017-02-15 16:21:37

标签: swift

我使用地图功能,必须将空字符串映射为nil,否则为字符串。问题是输入是否为?

var arr : Any? = ["hallo", "", nil, "hihi"]
let res = arr.map{ (($0 ?? "") as! String).isEmpty ? nil : $0 }
print(res)

你知道怎么做吗?

地图功能就在这里:

id <- (map["id"], TransformOf<Int, String>(fromJSON: { Int($0!) }, toJSON: { $0.map { String($0) } })) 

https://github.com/Hearst-DD/ObjectMapper#custom-transforms

2 个答案:

答案 0 :(得分:0)

你的意思是这样的:

var arr : Any? = ["hallo", "", nil, "hihi"]
if let array = arr as? [String?] {
    let result = array.map { ($0?.isEmpty ?? true) ? nil : $0 }
    print(result)
}

答案 1 :(得分:0)

存储数组Any?是有问题的,但如果你必须......

let arr: Any? = ["hallo", "", nil, "hihi"]

guard let casted = arr as? [String?] else {
    // handle error
    fatalError("arr is not a [String?]")
}

let result: [String?] = casted.map{
    guard let s = $0 else { return nil }
    return s.isEmpty ? nil : s
}

print(result as Any)