Manoj Kumar Manoj Kumar - 11 months ago 42
Swift Question

Will optional values be de-initialized automatically?

I am new to swift, please ignore if I am asking dumb questions ;)

Is it required to explicitly set optional values to nil, if they are not needed any more?
How about weak, strong reference works in swift?
What if the normal variables has to be de-initialized manually? Since there is no way to assign nil to normal variables in swift, someone please let me know how to do it.
What is the difference between?

var someVar:String? vs var someVar:String!

I see the only difference is in accessing them. The first prints values within the optional and second doesn't and the second throws exception when the value is nil. Is that only the difference?


Is it required to explicitly set optional values to nil

No, Automatic Reference Counting frees the memory automatically. Unless there is a circular reference, e.g., there is a strong reference to ClassA in ClassB and vice-versa. Also, Automatic Reference Counting only applies to instances of classes and not value types (String, Int, Enum, etc). The memory of these value types are freed when their parent instances are deinitialized.

Is that only the difference?

var someVar:String! creates an Implicitly Unwrapped Optional, which is basically an optional that is automatically unwrapped when accessed. Accessing an Implicitly Unwrapped Optional when it's nil causes a runtime error.