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?
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 ... } }
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.
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.
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.
You can simplify it into just one line:
private func addToUnloadedImagesRow(row: Int, forLocation:String!) {
unloadedImagesRows[forLocation] = (unloadedImagesRows[forLocation] ?? []) + [row]
}
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"
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