Skip to content

Instantly share code, notes, and snippets.

@lorentey
Created December 12, 2015 00:01
Show Gist options
  • Save lorentey/75bf5d5332895ee6ec7c to your computer and use it in GitHub Desktop.
Save lorentey/75bf5d5332895ee6ec7c to your computer and use it in GitHub Desktop.
You wouldn't expect calling a method on a class to modify the variable holding a reference to the instance, but it can happen.
//: Playground - noun: a place where people can play
import UIKit
protocol MagicProtocol {
}
extension MagicProtocol {
mutating func magic(xyzzy: Self) {
// Mutating methods defined in a protocol extension can mutate `self` even if
// the protocol is implemented by a class.
self = xyzzy
}
}
class MagicClass: MagicProtocol {
let value: Int
init(_ value: Int) { self.value = value }
}
func test() -> Bool {
var a = MagicClass(42)
let b = MagicClass(23)
a.magic(b)
return a === b
}
test()
@lorentey
Copy link
Author

This is very annoying when you're trying to create a proxy wrapping an array — a lot of everyday methods like insert and removeAtIndex are defined as mutable extension methods on a protocol like RangeReplaceableCollectionType. You cannot call them unless your proxy is declared in a var, even though (I hope) none of these methods actually try to modify self.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment