Swift-UserDefaults Extension

使用下标从UserDefaults获取对象

extension UserDefaults {
    public subscript(key: String) -> Any? {
        get {
            return object(forKey: key)
        }
        set {
            set(newValue, forKey: key)
        }
    }
}

从UserDefaults获取Float

extension UserDefaults {
    public func float(forKey key: String) -> Float? {
        return object(forKey: key) as? Float
    }
}

从UserDefaults获取Date

extension UserDefaults {
    public func date(forKey key: String) -> Date? {
        return object(forKey: key) as? Date
    }
}

从UserDefaults检索可编码对象

extension UserDefaults {
    /// - Parameters:
    /// - type: Class that conforms to the Codable protocol.
    /// - key: Identifier of the object.
    /// - decoder: Custom JSONDecoder instance. Defaults to `JSONDecoder()`.
    /// - Returns: Codable object for key (if exists).
    public func object(_ type: T.Type, with key: String, usingDecoder decoder: JSONDecoder = JSONDecoder()) -> T? {
        guard let data = self.value(forKey: key) as? Data   else { return nil }
        return try? decoder.decode(type.self, from: data)
    }
}

存储可编码对象到UserDefaults

extension UserDefaults {
    /// - Parameters:
    /// - object: Codable object to store.
    /// - key: Identifier of the object.
    /// - encoder: Custom JSONEncoder instance. Defaults to `JSONEncoder()`.
    public func set(object: T, forKey key: String, usingEncoder encoder: JSONEncoder = JSONEncoder()) {
        let data = try? encoder.encode(object)
        self.set(data, forKey: key)
    }
}

资源来自网络和日常整理,持续更新

你可能感兴趣的:(Swift-UserDefaults Extension)