Brian
Brian

Reputation: 8811

Swift: Using optional if statements correctly

So this doesn't work in Swift.

var a : Int? = 6   // simple mutable optional
if var b = a {
    b = 10         // naive assumption that a === b
}
print(a)           // prints 6, bad naive assumption

This is closer to my actual code, but still synthetic. So don't spend too much time on the structure. This doesn't work either.

if var employee = company[com]?.department[department]?.employees[name] {
    employee.flag = True 
}

I did this as an ugly workaround:

if var employee = company[com]?.department[department]?.employees[name] {
    company[com]!.department[department]!.employees[name]!.flag = True 
}

Is there a better way to write this?

Upvotes: 0

Views: 50

Answers (2)

Dan Karbayev
Dan Karbayev

Reputation: 2920

Dictionaries and arrays in Swift are structs which themselves are value types, thus, whenever you assign them or their elements to anything you're actually copying its value. Now, in your case you have two options:

  1. Use direct write to your dictionary:

    company[com]?.department[department]?.employees[name]
    
  2. Use classes instead of dictionaries and structures.

Off topic, if you had simple 1-level deep dictionary you could directly manipulate bytes of that dictionary (although you'd have to be super careful):

var dict: [String: Any] = [
  "a": 0,
  "b": 2
]
print(dict) // ["b": 1, "a": 0]

withUnsafeMutablePointer(to: &dict["b"]) { ptr in
  guard ptr.pointee != nil else { return }
  ptr.pointee = 2
}
print(dict) // ["b": 2, "a": 0]

Upvotes: 0

rmaddy
rmaddy

Reputation: 318784

You don't need the if let (or if var).

Just use optional chaining to set the value:

company[com]?.department[department]?.employees[name]?.flag = true

The problem with:

if var employee = company[com]?.department[department]?.employees[name] {
    employee.flag = True 
}

Is that you end up setting the flag of the local variable employee which is a copy of the original. By setting it directly you avoid all of the copies being done on the dictionaries/arrays/structs.

Upvotes: 3

Related Questions