Swift:Cachable一个协议抽象持久化

2,036 阅读3分钟

前言

之前在这篇文章里 我们定义了一个Parsable 用于反序列化

protocol Parsable {
  static func parse(data: Data) -> Result<Self>
}

如果我们要给自定义的类型添加一个持久化的功能,同样也可以定义一个协议,使得遵守这个协议的类型都拥有持久化这个功能。

Cachable

public protocol Cachable {
  /// 存入沙盒
  ///
  /// - Parameter path: 路径
  /// - Returns: 结果
  @discardableResult
  func save(at path: String) -> Result<Void, Error>

  /// 从沙盒中取
  ///
  /// - Parameter path: 路径
  /// - Returns: 结果
  static func get(fromCache path: String) -> Self?
}

Cachable定义了两个方法 存和取,接下来我们给Cachable添加默认实现。

Codable

大部分的反序列化与序列化都会使用非常方便Codable

extension Cachable where Self: Codable {
  @discardableResult
  public func save(at path: String) -> Result<Void, Error> {
    let url = URL(fileURLWithPath: path)
    do {
      let data = try JSONEncoder().encode(self)
      try data.write(to: url)
      return .success(())
    } catch {
      print("Cachable: 存储沙盒失败 - \(error.localizedDescription)")
      return .failure(error)
    }
  }

  public static func get(fromCache path: String) -> Self? {
    let url = URL(fileURLWithPath: path)
    do {
      let data = try Data(contentsOf: url)
      return try JSONDecoder().decode(self, from: data)
    } catch {
      print("Cachable: 从沙盒中获取失败 - \(error.localizedDescription)")
      return nil
    }
  }
}

如此一来当一个类型遵循了Codable且也想遵循Cachable就可以免费使用上面的两个方法。

struct Car: Codable {
  var engine: String
  var name: String
  var type: String
}

extenstion Car: Cachale {}

// 获取沙盒中缓存的car
let carCachePath = getMyCarCachePath()
let myCacheCar = Car.get(fromCache: carCachePath)

// 缓存bmw
let bmw = Car(engine: "V8", name: "X7", type: "xDrive50i")
bmw.save(at: carCachePath)

注:我们使用@discardableResult标记了save(at:)方法,目的是让编译器不警告我们没有使用save(at:)方法的返回值。很多链式调用的方法都有这个标记,例如Alamofire就使用了这个标记。

String、Data

我们也可以给StringData也添加这个功能。

extension Cachable where Self == String {
  @discardableResult
  public func save(at path: String) -> Result<Void, Error> {
    let url = URL(fileURLWithPath: path)
    do {
      if let data = self.data(using: .utf8) {
        try data.write(to: url)
        return .success(())
      } else {
        return .failure(WWError.stringToDataError)
      }
    } catch {
      print("Cachable: 存储沙盒失败 - \(error.localizedDescription)")
      return .failure(error)
    }
  }

  public static func get(fromCache path: String) -> Self? {
    let url = URL(fileURLWithPath: path)
    do {
      let data = try Data(contentsOf: url)
      return self.init(data: data, encoding: .utf8)
    } catch {
      print("Cachable: 从沙盒中获取失败 - \(error.localizedDescription)")
      return nil
    }
  }
}

Data也是一样的,大家可以自行去实现。

SwiftProtobuf

如果有使用SwiftProtobuf也可以给SwiftProtobufMessage添加这个功能。

extension Cachable where Self: SwiftProtobuf.Message {
  @discardableResult
  func save(at path: String) -> Result<Void, Error> {
    let url = URL(fileURLWithPath: path)
    do {
      let data = try serializedData()
      try data.write(to: url)
      return .success(())
    } catch {
      print("Cachable: 存储沙盒失败 - \(error.localizedDescription)")
      return .failure(error)
    }
  }

  static func get(fromCache path: String) -> Self? {
    let url = URL(fileURLWithPath: path)
    do {
      let data = try Data(contentsOf: url)
      return try self.init(serializedData: data)
    } catch {
      print("Cachable: 从沙盒中获取失败 - \(error.localizedDescription)")
      return nil
    }
  }
}

添加了默认实现后,我们的Cachable已经可以大展身手了,只要是满足Codable或是SwiftProtobuf里的Message并且遵循了Cachable就可以免费持久化了。

总结

protocol绝对是用来描述某种功能的利器,而且不受类型的限制,万物皆可遵循。想要JSON转model就遵循Decodable,想要持久化某个对象就遵循我们的Cachable...

只要你想提供某种功能,使用protocol抽象,给它添加默认实现,谁想用这个功能就遵循它,不想用也不会多余。