Reputation: 347
Getting the error of Immutable value of type '[String]' only has mutating member
in my swift project and researched some answers and none seem to fix the problem in my context. Take A Look:
import UIKit
class PassionViewController: UIViewController {
var factIndex = 0
var counter = 1
@IBOutlet var QuoteImage: UIImageView!
@IBOutlet weak var funFactLabel: UILabel!
let factBook = FactBook()
let Liked = Favourite()
override func viewDidLoad() {
super.viewDidLoad()
funFactLabel.text = factBook.factsArray[factIndex]
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func showFunFact() {
factIndex++
if (factIndex >= factBook.factsArray.count) {
self.factIndex = 0
}
funFactLabel.text = factBook.factsArray[factIndex]
if counter == 36 {
counter = 1
} else {
self.counter++
}
QuoteImage.image = UIImage(named: "frame\(counter).jpg")
}
@IBAction func goBack() {
factIndex--
var number = factBook.factsArray.count-1
if (factIndex < 0){
self.factIndex = number
}
funFactLabel.text = factBook.factsArray[factIndex]
if counter == 1 {
counter = 36
} else {
self.counter--
}
QuoteImage.image = UIImage(named: "frame\(counter).jpg")
}
@IBAction func Like() {
let currentQuote = factBook.factsArray[factIndex]
Liked.favouriteArray.append(currentQuote)
}
}
The let currentQuote = factBook.factsArray[factIndex], factBook.factsArray
is retrieved from another view controller which is a array collection. Liked.favouriteArray.append(currentQuote)
is to store this element into favouriteArray which is from a struct called Favourite:
import Foundation
struct Favourite {
var favouriteArray:[String] = []
}
However, the line Liked.favouriteArray.append(currentQuote) is generating the error: Immutable value of type '[String]' only has mutating member. How can I resolve this error?
Upvotes: 2
Views: 182
Reputation: 299265
It's unclear because you didn't provide the Favourite
type, but I assume it's either a struct
, or it's a class
that includes factsArray
as a let
variable. In either case, you're trying to modify a let
variable, which is not allowed (mutating an immutable value). Either liked
or factsArray
must be var
. (If Favourite
is a struct
, then liked
must be var
in either case.)
Note that Swift functions, methods, properties, and variables should start with a lowercase letter. Leading uppercase letters denote types.
Upvotes: 2