rohinb
rohinb

Reputation: 418

Unable to append String to array in Swift

So I am using this code and I get the error: Immutable value of type 'Array' only has mutating members named 'append.' I have been unable to find any working solutions as of yet.

import Foundation
struct Roster
{
    var names: Array<String>  = []

    func add(name: String) {
        names.append(name)
    }
}

Thank you!

Upvotes: 0

Views: 153

Answers (1)

Sandeep
Sandeep

Reputation: 21144

As the rule of immutable struct in swift, if you want to be able to modify the properties inside a method, you have to mark the method as mutating.

struct Roster
{
    var names: Array<String>  = []

    mutating func add(name: String) {
        names.append(name)
    }
}

Upvotes: 3

Related Questions