Skip to content

Instantly share code, notes, and snippets.

@takasek
Created January 20, 2018 07:16
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takasek/1c92935ceafb8340eb7fbc9d0f8379eb to your computer and use it in GitHub Desktop.
Save takasek/1c92935ceafb8340eb7fbc9d0f8379eb to your computer and use it in GitHub Desktop.
structのmutating funcでも、クロージャ内ではselfを書き替えることはできないよという話 #love_swift #CodePiece
struct A {
var hoge = "a" {
didSet { print("fixed", hoge) }
}
// たとえmutatingなfuncの中でも、
mutating func fix() {
// クロージャの中ではselfの書き換えはできない
DispatchQueue.main.async {
self.hoge = "b" // Error: Closure cannot implicitly capture a mutating self parameter
}
}
}
struct A {
var hoge = "a" {
didSet { print("fixed", hoge) }
}
mutating func fix() {
// こういうキャプチャすればselfをクロージャ内に持ち込むことはできるけど、
DispatchQueue.main.async { [zelf = self] in
// 持ち込んだ zelf は selfのイミュータブルなコピーであって、selfの書き換えはどのみちできない
zelf.hoge = "b" // Cannot assign to property: 'zelf' is an immutable capture
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment