[swift-users] Should Array's `append(_)` function cause `didSet`?
Zhao Xin
owenzx at gmail.com
Fri Jul 7 23:48:36 CDT 2017
Thank you very much Marco. But What is “outside of an initializer” really
bothers me. **Both** `func bar(keysAndValues:Dictionary<String, String>)`
works now. **Are they really outside ?**
struct Foo {
var keys = ["z","y","x"]
{
didSet {
keys.sort()
}
}
init(keysAndValues:Dictionary<String, String>) {
func bar(keysAndValues:Dictionary<String, String>) {
keys.append(contentsOf: keysAndValues.keys)
}
bar(keysAndValues:keysAndValues)
}
// private mutating func bar(keysAndValues:Dictionary<String, String>) {
// keys.append(contentsOf: keysAndValues.keys)
// }
}
let keysAndValues:Dictionary<String,String> = ["c":"c", "b":"b", "a":"a"]
var foo = Foo(keysAndValues: keysAndValues) // `let foo` is the same result
foo.keys.forEach { print($0) }
/*
prints
a
b
c
x
y
z
*/
Zhao Xin
On Sat, Jul 8, 2017 at 9:59 AM, Marco S Hyman <marc at snafu.org> wrote:
>
> > init(keysAndValues:Dictionary<String, String>) {
> > self.keys.append(contentsOf: keysAndValues.keys)
> > }
>
> >
> > Above code doesn't call `didSet` in playground. My .swift file is
> similar and didn't call `didSet` either. However, if without a struct,
> `didSet` is called.
>
> “If you don’t need to compute the property but still need to provide code
> that is run before and after setting a new value, use willSet and didSet.
> The code you provide is run any time the value changes outside of an
> initializer.”
>
> Excerpt From: Apple Inc. “The Swift Programming Language (Swift 3.1).”
> iBooks. https://itun.es/us/jEUH0.l
>
> Note “outside of an initializer”. didSet and willSet are not called in
> initializers.
>
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170708/19d02f66/attachment.html>
More information about the swift-users
mailing list