Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 972
ikevin8me Avatar asked Apr 12 '16 04:04

ikevin8me


People also ask

How to initialize an Object in Swift?

An initializer is a special type of function that is used to create an object of a class or struct. In Swift, we use the init() method to create an initializer. For example, class Wall { ... // create an initializer init() { // perform initialization ... } }

How check object is nil or not in Swift?

In Swift, you can also use nil-coalescing operator to check whether a optional contains a value or not. It is defined as (a ?? b) . It unwraps an optional a and returns it if it contains a value, or returns a default value b if a is nil.

How do I check if a variable is initialized in Swift?

There is no way to test for the use of an uninitialized non-optional variable at runtime, because any possibility of such use is a terrible, compiler-checked programmer error. The only code that will compile is code that guarantees every variable will be initialized before its use.

Can any be nil Swift?

Swift assumes by default that all variables have a value. Unless you tell it otherwise by declaring an optional you can't have a nil value in a place where your program expects there to be a value.


2 Answers

You can simplify it into just one line:

private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
    unloadedImagesRows[forLocation] = (unloadedImagesRows[forLocation] ?? []) + [row]
}
like image 136
Eendje Avatar answered Oct 24 '22 08:10

Eendje


You can create a helper operator for nil checks and use it like below.

infix operator ?= { associativity left precedence 160 }

func ?=<T: Any>(inout left: T?, right: T) -> T {
    if let left = left {
        return left
    } else {
        left = right
        return left!
    }
}

Here you will be able to use it like unloadedImagesRows[forLocation] ?= [Int]() if empty

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

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

addToUnloadedImagesRow(1, forLocation: "This is something")

print(unloadedImagesRows) // "["This is something": [1]]\n"
like image 2
Rahul Katariya Avatar answered Oct 24 '22 08:10

Rahul Katariya