Reputation: 5563
I was watching this video and at the 2 minute mark he explains somehting that I really don't understand.
Code:
class Order {
var product: Product?
}
class Product {
var order: Order?
}
var myOrder = Order()
var iPhone6 = Product()
myOrder.product = iPhone6
myOrder.product!.order = myOrder
He says, when talking about the explicit unwrapping, that if the property is null, the statement won't crash and get a null reference. He says the statement will have no effect if the product happens to be nil upon explicit unwrapping. I thought this was the case with using the question mark, like myOrder.product?.order
, but NOT with the exclamation point.
Upvotes: 0
Views: 182
Reputation: 4921
Straight to your question - here you are sure about creating your Order
instance so you don't have to check for nil
. But in other cases you will have to check for nil
.
What bothers me here is that you will have a retain cycle. So what you can make to avoid retain cycles is to keep weak reference to the Order
instance inside your Product
class (an order should always have a product but a product can go without an order). Something like this:
class Product {
weak var order: Order?
}
Upvotes: 2