so i have this simple code and have problem with swift data type, want to map this array from
["a", "b", nil, "c", "d", nil]
to
["a", "b", "z", "c", "d", "z"]
so, this is my current code
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)
I am grateful if you try to solve the code. thank you.
If you declare currentIndex
as Any
then you cannot compare it against nil
anymore. The correct type in your case would be String?
:
let newArray = array1.map { (currentIndex: String?) -> String in
if currentIndex == nil {
return "z"
}
return currentIndex!
}
However, the compiler can infer that automatically from the context:
let newArray = array1.map { currentIndex -> String in
if currentIndex == nil {
return "z"
}
return currentIndex!
}
Better use the nil-coalescing operator ??
, and avoid force-unwrapping:
let newArray = array1.map { currentIndex in
currentIndex ?? "z"
}
or shorter:
let newArray = array1.map { $0 ?? "z" }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With