Reputation: 2249
As far as i know the weak reference of swift is used because if the object gets nil and you call a method from it, it won't crash your application and just gets ignored. But isn't it a bad practice to allow some of your code to call a function on a not existing object of a class? Wouldn't it be cleaner to just avoid this scenario with good code?
Example what i mean:
weak var manager: MyManager?
manager.someFunction()
Now if the manger object is nil it just won't get called. I know it has it's easy to write code like this but is it really the best practice?
Sorry if this questions was asked before, but i only found explanations of weak and strong. I ask this because a friend of mine told me to use the weak reference to avoid an error call and i think that this is not the best way to handle nil objects because it seems like dirty code to me.
Upvotes: 0
Views: 372
Reputation: 28515
You have been given some misguided information.
Weak is not about making safe calls, but avoiding strong cycles between object instances that will cause memory leaks.
Safe calls are done with optional chaining.
var manager: MyManager?
manager?.someFunction() // this will not raise error if manager is nil
manager!.someFunction() // this raise error if manager is nil
Upvotes: 2
Reputation: 25632
The main point is that using weak
communicates something about ownership. It's also frequently used to prevent retain cycles.
That it nils out automatically is useful for some patterns like observing.
Calling methods on nil is a somewhat different topic, which often comes convenient and allows for cleaner (less cluttered, easier to read) code.
For doing more complex logic, you often assign the weak variable into a strong one, so that you can be sure that the whole code runs as you expect it to, and not suddenly works with nil in half the code.
Upvotes: 2