How to fix 'Cannot use mutating member on immutable value: 'self' is immutable' error in Xcode
I create a random number and assign it to the variable randomNumber
. Then when I try to append the random number as an index for the emojis
array to the empty array arrayOfEmojis
I get the error:
'Cannot use mutating member on immutable value: 'self' is immutable'
Im also getting errors from the emoji?
import GameKit
struct EmojiProvider {
var emojis = ["π", "π", "π", "π", "π", "π
", "π", "π€£", "βΊοΈ", "π", "π", "π", "π", "π", "π", "π"]
var arrayOfEmojis: [String]
func generateEmoji() -> [String] {
for i in 1...3 {
var randomNumber = GKRandomSource.sharedRandom().nextInt(upperBound: emojis.count)
arrayOfEmojis.append(emojis[randomNumber]) //error!
}
return arrayOfEmojis
}
}
This happens because when you have a struct
, instead of a class
, you're mutating the instance itself.
Hence, when you're trying to mutate self
, mark the function as mutating
:
mutating func generateEmoji() -> [String] {
Also, I suggest you select a random element as follows:
return (1...3).compactMap { _ in emojis.randomElement() }
...and leave our the whole arrayOfEmojis
, if you don't want to access it later.
The full code would then be:
struct EmojiProvider {
var emojis = ["π", "π", "π", "π", "π", "π
", "π", "π€£", "βΊοΈ", "π", "π", "π", "π", "π", "π", "π"]
mutating func generateEmoji() -> [String] {
return (1...3).compactMap { _ in emojis.randomElement() }
}
}
What you could also do, is make EmojiProvider
a class, instead of a struct.
You could then have the following code:
class EmojiProvider {
var emojis = ["π", "π", "π", "π", "π", "π
", "π", "π€£", "βΊοΈ", "π", "π", "π", "π", "π", "π", "π"]
func generateEmoji() -> [String] {
return (1...3).compactMap { _ in emojis.randomElement() }
}
}