【问题标题】:Accept a set of types in Swift在 Swift 中接受一组类型
【发布时间】:2022-08-03 16:03:19
【问题描述】:

我正在钥匙串的顶部做一个包装器。我想要一种存储字典的方法。我正在使用 Codable 协议将对象编码为数据。

我实际上并不真正想要将任何对象存储在字典中的代码,因为可以从代码中可能不知道相同自定义类的多个位置读取/写入数据(代码被拆分为框架)。因此,只接受原始类型(String、Bool、Float、Double、Integer),如果可能的话,数组或字典会很棒。

所以我的问题是:是否可以指定一个只接受像 [String: Raw] 这样的字典的方法,其中 Raw 是 (String| Bool | Float| Double | Integer | [Raw] | [String: Raw])?

我还尝试对 Codable 进行约束(我会在文档中禁止使用自定义类),代码如下:

func write<T: Codable>(param: [String: T]) {
    print(param)
}

func read<T: Codable>(of valueType: T.Type, for key: String) -> T {
    // read the data from the keychain
}

let param: [String: Int] = [
    \"key\": 0
]

write(param: param)
let integer = read(of: Int.self, for: \"key\")

有没有更好的方法来实现这一点?特别是,在这里我只能接受具有相同类型的值 ([String: String], [String, Int] ...),而不是 [String: (AnyObject & Codable)] 具有多个级别的结构,例如:

let structure: [String: Codable] = [
    \"forename\": \"John\",
    \"name\": \"Doe\",
    \"location\": [
        \"street\": \"Brooklyn av\",
        \"city\": \"New York\"
    ],
    \"phone\": 0123456789
]

    标签: swift generics keychain swift-protocols


    【解决方案1】:

    是的,有一种方法可以指定这样的方法:

    protocol Raw {}
    
    extension String: Raw {}
    extension Bool: Raw {}
    extension Float: Raw {}
    extension Double: Raw {}
    extension Int: Raw {}
    extension Array: Raw where Element: Raw {}
    extension Dictionary: Raw where Key == String, Value: Raw {}
    
    func write<T: Raw>(param: [String: T]) {
        print(param)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-13
      • 2019-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多