Swift nonmutating setters. an Oxymoron?

While going through Xcode 10.1 release notes I stumbled upon a very unfamiliar term “nonmutating setters”. Inquisitiveness had the best of me and I spent time reading about it and implementing examples. Here is the jest for you

  • nonmutable setters cannot be used within Classes or protocol bound classes
  • nonmutable setters do not mutate instance
  • nonmutable setters have side effects which go beyond the instance

Example of a nonmutating setter and a use

enum ExampleEnum:String{
    case URL,UserName
    var value:String{
        get{
            return UserDefaults.standard.value(forKey: self.rawValue) as? String ?? ""
        }
        nonmutating set(newValue){
            UserDefaults.standard.set(newValue, forKey: self.rawValue)
        }
    }
}

//It can be used as 
 ExampleEnum.UserName.value = "yoooo"
print(ExampleEnum.UserName.value)

 

A pat on the back !!