Reputation: 62529
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
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
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
Reputation: 285132
You could use optional chaining
if let myView = (cell as? AECell).someView {
if !myView.hidden{
// do something
}
}
Upvotes: 0
Reputation: 8184
if let myCell = cell as? AECell, let someView = myCell.someView {
// someView is unwrapped now
}
Upvotes: 1