David Seek David Seek - 1 month ago 18
Swift Question

How to solve: constructor parameter immutable

To refactor a function, I'm trying to put it globally available:

func loadUsers(_ users: [User] , _ tableView: UITableView) {

let usersRef = firebase.child("Users")
usersRef.observe(.value, with: { snapshot in
if snapshot.exists() {

users.removeAll()
...
}


I'm receiving:


Cannot use mutating member on immutable value: 'users' is a 'let' constant


When I set:

func loadUsers(_ users: [User] , _ tableView: UITableView) {

let usersRef = firebase.child("Users")
usersRef.observe(.value, with: { snapshot in
if snapshot.exists() {

if var users = users as? [User] {
users.removeAll()
...
}


It builds and works, but I receive constantly the warnings:


Conditional cast from '[User]' to '[User]' always succeeds

And
Non-optional expression of type '[User]' used in a check for optionals


What is the best approach to solve my issue? Help is very appreciated.

PS, I need the original values from
users
to be removed.

Answer

The error in the first set of code is because parameters are immutable.

The errors in the second set of code are because you are trying to use if let with a non-optional constant and you are trying to cast to the same type making the cast pointless.

Since you want the original array to be modified by this function you need to make it an inout parameter:

func loadUsers(_ users: inout [User] , _ tableView: UITableView) {
    let usersRef = firebase.child("Users")
    usersRef.observe(.value, with: { snapshot in
        if snapshot.exists() {
            users.removeAll()
            ...
}

You now also need to add an & before the var that you pass to the users parameter.