avechuche
avechuche

Reputation: 1560

Array of custom objects - Swift

I have this piece of code, I have a problem trying to create an array of users.

if I use "var userArray: [Users] = FakeData" gives me the following error "Can not convert value of type 'User_TableViewController -> () -> [Users]' to specified type '[Users]'"

if I use "var userArray: [Users] = FakeData()" gives me the following error "Missing argument for parameter # 1 in call"

if I use "var userArray: [Users] = [FakeDate]" I get the following error "Use of unresolved identifier 'FakeDate'"

What is the problem? I ran out of ideas xD

class User_TableViewController: UITableViewController {

    var userArray:[Users] = FakeData()

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return userArray.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let Cell = tableView.dequeueReusableCellWithIdentifier("userCell") as! UserCell_TableViewCell
        Cell.userImage.image = userArray[indexPath.row].getImage()
        Cell.userDescription?.text = userArray[indexPath.row].getFirstName()

        return Cell
    }

    func FakeData() -> [Users]{

        let Person1 = Users(firstName: "Usuario 1", lastName: "Apellido 1", email: "[email protected]", password: "1234567", age: "18", gender: "Male", image: UIImage(named: "Apple48x48")!)
        let Person2 = Users(firstName: "Usuario 2", lastName: "Apellido 2", email: "[email protected]", password: "1234567", age: "18", gender: "Male", image: UIImage(named: "Apple48x48")!)
        let Person3 = Users(firstName: "Usuario 3", lastName: "Apellido 3", email: "[email protected]", password: "1234567", age: "18", gender: "Male", image: UIImage(named: "Apple48x48")!)

        return [Person1, Person2, Person3]

    }

}

Upvotes: 0

Views: 918

Answers (1)

shim
shim

Reputation: 10158

You should be initializing the array inside a method, like viewDidLoad or init. For the property declaration either set

var userArray:[Users]!

or

var userArray:[Users] = []

Then inside (for example) viewDidLoad:

userArray = FakeData()

(Also convention is to name methods starting with lowercase letters, so fakeData(), in one of your attempts you wrote FakeDate instead of FakeData, and also variable names should also start with a lowercase letter i.e. cell not Cell)

Upvotes: 2

Related Questions