Created
January 20, 2018 07:16
-
-
Save takasek/1c92935ceafb8340eb7fbc9d0f8379eb to your computer and use it in GitHub Desktop.
structのmutating funcでも、クロージャ内ではselfを書き替えることはできないよという話 #love_swift #CodePiece
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
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