Cannot use mutating member on immutable value of type
When you apply type casting to value types (such structs), if succeed, you receive immutable copy of requested value:
(self.data as! ModelOne) // this is copy of data
The only way (as known to me) how you can mutate values that need to be casted - reassign value (as @Sahil Beri pointed you need declare variable):
func someFunc() {
if var data = data as? ModelOne {
data.setSub(ModelOne.SubModelOne(someVar: 2, otherVar: 1))
self.data = data // you can do this since ModelOne conforms to SuperModel
}
}
How to fix 'can not use mutating member on immutable value'?
Well, you also have a problem of removing elements from the array and then going beyond its bounds. Try it like this:
func removeInPlace(item: Int, fromArray: inout [Int]) -> Void {
for i in stride(from: fromArray.count - 1, to: 0, by: -1)
{
if fromArray[i] == item {
fromArray.remove(at: i)
}
}
}
var anarray : [Int] = [1, 2,3, 4 ,3]
var x = 3
print(anarray) // prints [1, 2, 3, 4, 3]
removeInPlace(item: x, fromArray: &anarray)
print(anarray) // prints [1, 2, 4]
You'll want additional error handling, but hope this helps get you on your way.
Cannot use mutating member on immutable value: Error in Swift
var quarantineStuff: [String] = ["zero to one book", "proper twelve whiskey",
"coffee", "tonic water", "toilet roll", "broken electronics"]
func removeItemsICantTakeWithMe(list: [String]) -> [String] {
var aList = list // method object is immutable so we have to make a mutable object
if let index = aList.firstIndex(of: "toilet roll") {
aList.remove(at: index)
}
return aList
}
let renewedList = removeItemsICantTakeWithMe(list: quarantineStuff)
print(renewedList)
Cannot use mutating member on immutable value of type '[...]'
The following should work.
let nodeTypes = [smoothstepNodeType].sorted(by: {$0.name < $1.name})
Hop it's what you need.
Cannot modify my array - Cannot use mutating member on immutable value: function call returns immutable value
As the error tells you, your findPerson
method is returning an immutable struct, so you can't edit it.
There are a few solutions to this -- two are included in the code sample below:
final class City {
var people = [Person]()
func addPetFor(id: UUID, newPets: [String]) {
guard let index = self.people.firstIndex(where: { $0.id == id }) else {
assertionFailure("Not found")
return
}
self.people[index].pets.append(contentsOf: newPets)
}
func addPetFor2(id: UUID, newPets: [String]) {
self.people = self.people.map {
if $0.id == id {
var personCopy = $0
personCopy.pets.append(contentsOf: newPets)
return personCopy
} else {
return $0
}
}
}
}
In both cases, the code has a reference to where the Person
belongs in the people
array, so it can modify it. Note that people
also has to be var
, not let
, for the same reason -- it needs to be mutable.
Cannot use mutating member on immutable value of type 'String'
You need to understand the difference between a non-mutating function that returns a value, and a void mutating function. The one you wrote, is a mutating function:
mutating func parent(_ word:String){
self = self+" "+word
}
Mutating functions like this can be used like this:
var string = "Hello"
string.parent("World")
print(string)
As you can see, the call to parent
changes the value that is stored in the variable string
.
Function that returns is another matter. This is the same parent
function, rewritten to return a value:
func parent(_ word: String) -> String {
return self + " " + word
}
You can use this function that returns like this:
print("Apple".parent("Tree"))
print("Tomato".parent("Plant"))
In this case, nothing is being changed. Values are just being "computed" and returned to the caller.
What you are doing wrong is basically trying to use a mutating function like a function that returns.
To fix this, either change the function to return a value, or use the mutating function properly, as I've showed you.
Cannot use mutating member on immutable value error when modifying a struct
By default variables defined in the for
are let
and they cannot be altered. So you have to make it a var.
Easier solution:
for var section in sections {
if let i = section.offers.index(where: { $0.id == offer.id }) {
section.offers.remove(at: i)
}
}
Swift(UI) Error: Cannot use mutating member on immutable value: 'self' is immutable
Views are immutable in SwiftUI. You can only mutate their state, which is done by changing the properties that have a @State
property wrapper:
@State var entries: [CEntries] = []
However, while you could do that, in your case CEntries
is a class - i.e. a reference type - so while you could detect changes in the array of entries
- additions and removals of elements, you won't be able to detect changes in the elements themselves, for example when .string1
property is updated.
And it doesn't help that it's an ObservableObject
.
Instead, change CEntries
to be a struct
- a value type, so that if it changes, the value itself will change:
struct CEntries: Identifiable {
var id: UUID = .init()
var string1 = ""
var string2 = ""
}
struct AView: View {
@State var entries = [CEntries]()
var body: some View {
VStack() {
ForEach(entries) { entry in
VStack {
Text(entry.string1)
Text(entry.string2)
}
}
Button(action: {
self.entries.append(CEntries(string1: "he", string2: "lp"))
}) {
someButtonStyle()
}
}
}
}
Related Topics
Pass Data from Tableviewcontroller to Another Tableviewcontroller in Swift
Could Not Find an Overload for '-' That Accepts The Supplied Arguments
Osx/Swift: Call a Function When Internet Connection Is Established/Restored
Swiching Between 2 Diferent Nsviewcontrollers with Data
Updating Existing Constraints Does Not Work, Wrong Use of .Active Property
Uisearchcontroller Hiding Status Bar on iOS 11 Swift 4
How to Remove The Fading Animation on .Ondelete Swiftui
Nssavepannel - How to Restrict User to Only Save One One Set Directory
Nsnumber/Nsdecimalnumber Bizarre Behavior
How to Resolve Rctpromiseresolveblock After Bftask
Customize Mglpolyline Using Mapbox
Touch Sprite, Make It Jump Up Then Fall Down Again(Repeat as Many Times as Spritenode Is Tapped.)
Mkpolyline Broken When Using Type Satelliteflyover
Access Safari Bookmarks in Macos Mojave Programmatically
Indent Second Line of UIlabel (Swift)
Swift Pattern Match on Array<Any>
Cleanly Handling /Usr/Local/ with Swift Package Manager and Libevent