Home > database >  How do i add objects into an array from a Class in Swift?
How do i add objects into an array from a Class in Swift?

Time:11-20

This is my Friend class:

class Friend {
    var firstName: String = ""
    var lastName: String = ""
    var age: Int = 0
    var description:String = ""

    init(firstname: String, lastname: String, age: Int) {
        self.firstName = firstname
        self.lastName = lastname
        self.age = age
    }
}

This is where i'm supposed to declare and instantiate 5 Friend objects in the viewDidLoad function and to add them into 'friendList' array.

import UIKit

class ViewController: UIViewController {

    var friendsList: [Friend] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        friendsList.append("John", "Doe", 20)
    }
}

Swift tells me that "No exact matches in call to instance method 'append'" on the "friendsList.append" line.

CodePudding user response:

you can use like Below if you are creating all friends Initially

 let friends = [Friend(firstname: "John", lastname: "Doe", age: 20),Friend(firstname: "doe", lastname: "John", age: 21)]
    
    for friend in friends{
        friendsList.append(friend)
    } 
//////////////////////////////////////
 (or) you can directly declare value for your global variable  

friendsList = [Friend(firstname: "John", lastname: "Doe", age: 20),Friend(firstname: "doe", lastname: "John", age: 21)]
///////////////////////////////////////////

(or) assign local variable value to your global variable
friendsList = friends

or if you adding One by One,You have to create object first

  let friendOne = Friend(firstname: "John", lastname: "Doe", age: 20)
    friendsList.append(friendOne)

CodePudding user response:

The Array (Actually collection) function append takes a parameter of type <T> where T is a generic type, "the type of the elements in the array".

So if you have an array of Strings, you need to pass a String into append:

var strings = [String]()

strings.append("a string")

Since you have an array of Friend objects, you need to pass an instance of Friend to the append(_:) function. Does the expression inside the parentheses in your call to append evaluate to a friend object?

friendsList.append("John", "Doe", 20)

It doesn't. You'r passing a comma-separated list of properties. Presumably, those are the first name, last name, and age of a Friend, but the append() function doesn't know that.

You could write it as:

let aFriend = Friend(firstname: "John", lastname: "Doe", age: 20)
friendList.append(aFriend)

Or all in one line with:

friendList.append(Friend(firstname: "John", lastname: "Doe", age: 20))

Both of those variations would work.

  • Related