Created
December 12, 2015 00:01
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is very annoying when you're trying to create a proxy wrapping an array — a lot of everyday methods like
insert
andremoveAtIndex
are defined as mutable extension methods on a protocol likeRangeReplaceableCollectionType
. 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.