mutating func in Swift only for value type

Divesh Singh
1 min readSep 19, 2019

--

In Swift for value type, self is always constant. That why it’s now allowed to modify the property, Using mutating mean it will create new copy where we can modify the properties.

mutating Keyword used with only with Value type like struct and enum, where we can not modify the property of member directly like class.

In the below example one strut created with the properties ageList:

struct Student {

public var ageList = [Int]() // Empty items list

}

So to modify the properties (ageList) of Student (struct) in above example we have to create one function with mutating keyword.

In other words In order to modify the properties of a value type, you have to use the in the instance method.

--

--

Divesh Singh
Divesh Singh

Written by Divesh Singh

Postgraduate from JEC Jabalpur || iOS and macOS developer, traveler |||| EM at Darwinbox | Ex-Samsung || Ex - Optimize IT Sys | Ex - R Systems

No responses yet