Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strong and weak references in Swift

In Objective C you can define a property as having a strong or weak reference like so:

@property(strong)... @property(weak)... 

How is this done in swift?

like image 846
67cherries Avatar asked Jun 03 '14 13:06

67cherries


People also ask

What are strong and weak references?

A weak reference is just a pointer to an object that doesn't protect the object from being deallocated by ARC. While strong references increase the retain count of an object by 1, weak references do not. In addition, weak references zero out the pointer to your object when it successfully deallocates.

What is a weak reference in Swift?

Weak References. A weak reference is a reference that doesn't keep a strong hold on the instance it refers to, and so doesn't stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle.

What is the difference between strong reference and weak reference?

If you have a strong reference to an object, then the object can never be collected/reclaimed by GC (Garbage Collector). If you only have weak references to an object (with no strong references), then the object will be reclaimed by GC in the very next GC cycle.

What is the difference between strong and weak references in IOS?

strong is the default. An object remains “alive” as long as there is a strong pointer to it. weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.


1 Answers

Straight from the Swift Language guide:

class Person {     let name: String     init(name: String) { self.name = name }     var apartment: Apartment?     deinit { println("\(name) is being deinitialized") } }  class Apartment {     let number: Int     init(number: Int) { self.number = number }     weak var tenant: Person?     deinit { println("Apartment #\(number) is being deinitialized") } } 

properties are strong by default. But look at the tenant property of the class "Apartment", it is declared as weak. You can also use the unowned keyword, which translates to unsafe_unretained from Objective-C

https://itunes.apple.com/tr/book/swift-programming-language/id881256329?mt=11

like image 103
Kaan Dedeoglu Avatar answered Oct 14 '22 11:10

Kaan Dedeoglu