Swift - trouble appending array from class

前端 未结 1 1501
不思量自难忘°
不思量自难忘° 2021-01-15 23:45

I am having trouble understanding why the following code is replacing all of my array elements with the latest information when I am trying to just append it.

I ha

相关标签:
1条回答
  • 2021-01-16 00:10

    You are passing data to the array by reference, and in every loop you change the value of the reference:

    self.aUser.username = object["username"] as! String
    self.usersAvailableArray.append(self.aUser)
    

    Try to create a new user every time:

    var newUser = usersAvailable()
    newUser.username = object["username"] as! String
    self.usersAvailableArray.append(newUser)
    

    This is happening because the object you are append come from a class, from appe documentation:

    Classes Are Reference Types

    Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used instead. You can see more about values and references in Swift

    Another solution is to change your class to a struct, like below, structs different if classes make a copy of the value when it is passes instead pass a reference.

    struct usersAvailable {
        var username = String()
        var userAvatar = UIImage()
    }
    
    0 讨论(0)
提交回复
热议问题