如何使用Swift 3摆脱`UserDefaults`中的`forKey`字符串文字?

时间:2016-08-31 20:47:21

标签: ios swift nsuserdefaults

我厌倦了在使用coolFeatureEnabled时重复无数UserDefaults字符串文字。如果有一个很好的方法来摆脱它们与Swift 3?

var coolFeatureEnabled: Bool {
    get { return UserDefaults.standard.bool(forKey: "coolFeatureEnabled") }
    set { UserDefaults.standard.set(newValue, forKey: "coolFeatureEnabled") }
}

1 个答案:

答案 0 :(得分:1)

以下是如何在Swift 3中避免使用#function的字符串文字

// a little bit of setup

private func getBool(key: String = #function) -> Bool {
    return UserDefaults.standard.bool(forKey: key)
}

private func setBool(_ newValue: Bool, key: String = #function) {
    UserDefaults.standard.set(newValue, forKey: key)
}


// and here is the fun part

var coolFeatureEnabled: Bool {
    get { return getBool() }
    set { setBool(newValue) }
}

var anotherFeatureEnabled: Bool {
    get { return getBool() }
    set { setBool(newValue) }
}

...