j2emanue
j2emanue

Reputation: 62529

Swift - how to make inner property optional

My question is in regards to optionals in swift. Let say i have the following defined already:

if let myCell = cell as? AECell {
    if !myCell.someView.hidden{
        //how do i use optional on someView, perhaps someView will not exists
    }
}

as you can see, what if someView is nil , how do i use an optional here to only execute the if statement if someView is not nil ..i tried the question mark: if !myCell.someView?.hidden but its syntax is not correct

Upvotes: 0

Views: 75

Answers (4)

0x416e746f6e
0x416e746f6e

Reputation: 10136

This should do it:

if let myCell = cell as? AECell, let myView = myCell.someView where !myView.hidden {
    // This gets executed only if:
    // - cell is downcast-able to AECell (-> myCell)
    // - myCell.myView != nil (-> unwrapped)
    // - myView.hidden == false
}

Upvotes: 0

user1078170
user1078170

Reputation:

To answer the question directly, yes you can use optionals this way. The someView property of your cell must be defined as optional.

class MyCell: UICollectionViewCell {
  var someView: AECell?
}

Then you can use the following syntax:

myCell.someView?.hidden = true

The behavior you're talking about is very much akin to Objective-C's nil messaging behavior. In Swift,you want to lean more towards confirming the existence of an object before manipulating it.

guard let myView = myCell.someView as? AECell else {
  // View is nil, deal with it however you need to.
  return
}
myView.hidden = false

Upvotes: 0

vadian
vadian

Reputation: 285132

You could use optional chaining

if let myView = (cell as? AECell).someView {
    if !myView.hidden{
        // do something
    }
}

Upvotes: 0

Andrius Steponavičius
Andrius Steponavičius

Reputation: 8184

if let myCell = cell as? AECell, let someView = myCell.someView {
    // someView is unwrapped now
}

Upvotes: 1

Related Questions