Skip to content
Advertisement

Adding a newly created object into an array in swift

I decided to start a project in java to get a rough outline of how the program was to function before I started to program it in swift(a language I am completely unfamiliar with) whilst trying to convert the code I’ve ran into an issue and cannot even understand how I’ve gone wrong. This is context for the code

public class Item {
    private String name;
    private double price;

    public Item(String name,double price) {
        this.name = name;
        this.price = price;
    }
}
public class Account{
    public ArrayList<Item> ItemsList = new ArrayList<Item>();
   
    public Account() {
        this.ItemsList = newArrayList<Item>();
    }

    public void addItem(String name,double price) {
        ItemsList.add(new Item(name,price))
    }

In Swift I’ve got this far

class Item {
    
    var name:String
    var price:Double
    
    init(name:String,price:Double) {
        self.name = name
        self.price = price
    }
}

class Account {

    var ItemsList:Array<Item>

    init() {
        self.ItemsList = []
    }

    func addItem(name: String,price: Double){
        ItemsList.append(Item(name: String,price: Double))
    }

}

but the final line

ItemsList.append(Item(name: String,price: Double))

is returning an error when running

Advertisement

Answer

The problem is here

func addItem(name: String, price: Double){
     ItemsList.append(Item(name: String,price: Double)) //<-- Problem
}

Look at it JAVA code:

public void addItem(String name,double price) {
       ItemsList.add(new Item(name,price) //<-- Here
}

Your passing name and price as a value parameter, not a data type.

Why you get an error? It because when you call any function you need to pass value instead of Data Type

The correct syntex is :

func addItem(name: String, price: Double){
    ItemsList.append(Item(name: name, price: price)) //<-- Solution
}

If you want to JAVA type constructor syntax style, you can use underscore like this,

class Item {
    var name: String
    var price: Double
    init(_ name:String, _ price:Double) {
        self.name = name
        self.price = price
    }
}

class Account {
    var itemsList: [Item] = []
    
    init() {
    }
    
    func addItem(name: String, price: Double){
        itemsList.append(Item(name, price))
    }
    
}

Note: Variable name must start with lower case. More: https://google.github.io/swift/

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement