Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning a reference from a class member to variable in Swift

class UserDataStore {
}

class ProfileInteractor {

    var userDataStore: UserDataStore?

    init(userDataStore: UserDataStore?) {
        self.userDataStore = userDataStore
    }
}

var profileInteractor = ProfileInteractor(userDataStore: UserDataStore())
var userDataStore = profileInteractor.userDataStore
profileInteractor.userDataStore = nil

print(profileInteractor.userDataStore == nil) // prints: true
print(userDataStore == nil) // prints: false
print(userDataStore === profileInteractor.userDataStore) // prints: false
  • Can anyone please explain, why userDataStore doesn't point to profileInteractor.userDataStore !?
  • What must I do, that userDataStore points to it?
like image 354
twofish Avatar asked Dec 15 '25 05:12

twofish


1 Answers

I think that you are misunderstanding the purpose of assigning nil to userDataStore.

Assigning userDataStore to nil means that it will not point to anything, i.e it will be destroyed; That should not leads to let profileInteractor.userDataStore to be also nil. nil in Swift means that there is nothing at all, it does not mean that it is a pointer to an empty space in the memory.

To make it more clear, check the following code snippet:

class UserDataStore: CustomStringConvertible {
    var title: String?

    var description: String {
        return "\(title)"
    }

    init(_ title: String) {
        self.title = title
    }
}

class ProfileInteractor {

    var userDataStore: UserDataStore?

    init(userDataStore: UserDataStore?) {
        self.userDataStore = userDataStore
    }
}

var profileInteractor = ProfileInteractor(userDataStore: UserDataStore("Hello"))
var userDataStore = profileInteractor.userDataStore

print(userDataStore === profileInteractor.userDataStore) // prints: true
print(profileInteractor.userDataStore) // prints: Optional(Optional("Hello"))

userDataStore?.title = "Bye"

print(profileInteractor.userDataStore) // prints: Optional(Optional("Bye"))

userDataStore = nil

print(profileInteractor.userDataStore) // prints: Optional(Optional("Bye"))

Hope this helped.

like image 165
Ahmad F Avatar answered Dec 16 '25 21:12

Ahmad F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!