ikevin8me ikevin8me - 6 months ago 13
Swift Question

Swift language: nil check, and if so instantiate new object

Is there any way I can simplify this:

var unloadedImagesRows = [String:[Int]]()

private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
if unloadedImagesRows[forLocation] == nil {
unloadedImagesRows[forLocation] = [Int]()
}
unloadedImagesRows[forLocation]!.append(row)
}


Doesn't Swift have an easy way to check for
nil
, and if so, create a new object, and all subsequent uses refers to the object?

Answer

You can simplify it into just one line:

private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
    unloadedImagesRows[forLocation] = (unloadedImagesRows[forLocation] ?? []) + [row]
}