简体   繁体   English

Swift抽象返​​回类型的方法

[英]Swift abstract return type of method

I wanna to create a function that returns a value an array from the UserDefauts, like this: 我想创建一个从UserDefauts返回一个数组值的函数,如下所示:

func GetBool(name: String) -> Bool {
    let defaults = UserDefaults.standard
    return defaults.bool(forKey: name)
}

func GetBoolArray(name: String) -> [Bool] {
    let defaults = UserDefaults.standard
    return defaults.array(forKey: name) as? [Bool] ?? [Bool]()
}

But I don't wanna create a function for Bool, another for Int, another for CGFloat, etc. 但是我不想为Bool创建函数,为Int创建另一个函数,为CGFloat创建另一个函数,等等。

What's the best way to abstract all functions (for Bool, Int, etc.) into one (one for single values, other for array values)? 将所有函数(用于Bool,Int等)抽象为一个(一个用于单个值,另一个用于数组值)的最佳方法是什么?

Would something like this work for you? 这样的事情对您有用吗?

func GetValue(name: String) -> Any? {
    let defaults = UserDefaults.standard
    return defaults.value(forKey: name)
}

func GetValueArray(name: String) -> [Any] {
    let defaults = UserDefaults.standard
    return defaults.array(forKey: name) ?? [Any]()
}

Note that the first function needs to be unwrapped when used because the key you used might not match a value. 请注意,使用第一个函数时,需要将其解包,因为您使用的键可能与值不匹配。 Also, I believe array for key works with NSArrays only so the first function would probably work for both cases for you. 另外,我相信键阵列只能与NSArrays一起使用,因此第一个函数可能对您都适用。

Thanks to @Martin R, I discovered swift generics, this is what I was looking for 感谢@Martin R,我发现了快速的泛型,这就是我想要的

func GetValue<T>(name: String) -> T {
    let defaults = UserDefaults.standard
    return defaults.value(forKey: name) as! T
}

func GetArray<T>(name: String) -> [T] {
    let defaults = UserDefaults.standard
    return defaults.array(forKey: name) as? [T] ?? [T]()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM