简体   繁体   中英

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: "mail1@hotmail.com", password: "1234567", age: "18", gender: "Male", image: UIImage(named: "Apple48x48")!)
        let Person2 = Users(firstName: "Usuario 2", lastName: "Apellido 2", email: "mail2@hotmail.com", password: "1234567", age: "18", gender: "Male", image: UIImage(named: "Apple48x48")!)
        let Person3 = Users(firstName: "Usuario 3", lastName: "Apellido 3", email: "mail3@hotmail.com", password: "1234567", age: "18", gender: "Male", image: UIImage(named: "Apple48x48")!)

        return [Person1, Person2, Person3]

    }

}

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 ie cell not Cell)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM