Many Swift initializers return non optional objects. This means the cannot be nil
and are always successful. However, behind the scenes, Swift has to allocate memory, and it is in general possible for memory allocation to fail. For example, memory returned by C function malloc()
should be checked for NULL
.
- How/why can Swift guarantee that object memory allocation will be successful, as implied by a non optional initializer return?
- What happens if I try to instantiate a Swift object in the minuscule but nonzero chance that the system that is out of memory?
CodePudding user response:
You ask:
How/why can Swift guarantee that object memory allocation will be successful, as implied by a non optional initializer return?
It can't.
What happens if I try to instantiate a Swift object in the minuscule but nonzero chance that the system that is out of memory?
Generally, it will just crash.
Fortunately, the app will often receive memory warnings before it gets to that point (at least if the app is consuming memory slowly enough for the OS to have a chance to supply a warning). So apps often have a chance to free up a little memory before everything goes south. And suspended apps may be jettisoned to free up a little memory, too.
But Swift does not gracefully handle these degenerate scenarios. We are often stuck looking at crash reports, looking for memory related crashes. And when we have memory issues, they often manifest in inconsistent errors (i.e., not always the same line of code), but there are tricks to identify the source of the problem. We will also often “profile” our apps periodically with Instruments to identify memory issues.