Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 4 Array Map nil to String

Tags:

arrays

swift

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.

like image 514
Pengguna Avatar asked Dec 27 '18 09:12

Pengguna


1 Answers

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"  }
like image 175
Martin R Avatar answered Sep 27 '22 20:09

Martin R