目录

Swift中Double Protocol Conformance的陷阱

前言

一般情况下,我们修复问题都会将我们能想到的错误case处理,但有时还是会有意想不到的副作用产生。这篇文章介绍的就是Double Protocol Conformance带来的问题

什么是 Double Protocol Conformance

简单说就是一个类型被声明多次遵循相同协议

swift 复制代码
// Item 已经遵循了Codable协议
public struct Item: Codable { } 
// Error: Redundant conformance of 'Item' to protocol 'Decodable'
// Error: Redundant conformance of 'Item' to protocol 'Encodable'
// Item 的扩展遵循了Codable协议
extension Item: Codable { }

如果我们在同一个Target里面书写上面的代码会报错

有趣的部分

  1. 我们在同一个Target里面,对一个类型和这个类型的扩展同时声明遵循相同协议,Xcode编译器会检测出来并报错
  2. 但当我们在不同的Target里分别对一个类型和这个类型的扩展声明遵循相同协议时,Xcode就检测不出来了

在TargetA中声明Item遵循Codable,并使用编译器的默认实现

swift 复制代码
// TargetA
public struct Item: Codable { 
    public let id: UUID
    public let name: String 
    public init(id: UUID, name: String) { 
        self.id = id 
        self.name = name 
    }
}

在TargetB中引入TargetA,并在Item的扩展中声明遵循Codable协议,自定义实现编解码

swift 复制代码
// TargetB
import Foundation
import TargetA 
extension Item: Codable { 
    // MARK: - Coding Keys 
    enum CodingKeys: String, CodingKey {
        case id = "product_id"
        case name = "product_name"
    } 
    // MARK: - Encodable 
    public func encode(to encoder: Encoder) throws { 
        var container = encoder.container(keyedBy: CodingKeys.self) 
        try container.encode(id, forKey: .id) 
        try container.encode(name, forKey: .name) 
    } 
    // MARK: - Decodable 
    public init(from decoder: Decoder) throws { 
        let values = try decoder.container(keyedBy: CodingKeys.self) 
        let id = try values.decode(UUID.self, forKey: .id) 
        let name = try values.decode(String.self, forKey: .name) 
        self = .init(id: id, name: name) 
    }
}

此时Xcode不会报错,而只会弹出警告。但就隐藏着问题了。只要代码能Run,我们就会认为没啥问题

暴露问题

假设我们有3个Target

  1. TargetA里面声明了Item,但是没有遵循Codable协议
  2. TargetB依赖TargetA,并在Item的扩展中遵循了Codable协议
  3. TargetC依赖TargetA,并未依赖TargetB,也在Item的扩展中遵循了Codable协议

看起来我们的代码好像没啥问题,我们也很难觉察到有Double Protocol Conformance的问题

如果我们在另外的Target里引入了TargetA、TargetB、TargetC,引入的顺序会影响最终的实现

swift 复制代码
// 先引入B再引入C
import TargetA
import TargetB
import TargetC 
let item = Item(id: .init(), name: "My Item") 
let encoder = JSONEncoder()
let encoded = try encoder.encode(item)
let jsonString = String(data: encoded, encoding: .utf8)

/** 输出的结果如下
{ 
    "product_name_B": "My Item", 
    "product_id_B": "42A18A37-51FA-422C-9BB9-46D382CDF1CA"
}
*/
swift 复制代码
// 先引入C再引入B
import TargetA
import TargetC
import TargetB
let item = Item(id: .init(), name: "My Item") 
let encoder = JSONEncoder()
let encoded = try encoder.encode(item)
let jsonString = String(data: encoded, encoding: .utf8)

/** 输出的结果如下
{ 
    "product_name_C": "My Item", 
    "product_id_C": "42A18A37-51FA-422C-9BB9-46D382CDF1CA"
}
*/
  1. 从上面的例子中,我们可以知道当一个类在不同的Target中同时遵循协议的时候,采用的是实现是第一个import中的实现
  2. 我们一般在工作中都是模块化的,会比例子里面的情况更复杂。所以对于协议遵循指定一套规则是很重要的

资料

alexanderweiss.dev/blog/2023-0...

本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
Swift社区1 小时前
从表格到序列:Swift 如何优雅地解 LeetCode 251 展开二维向量
开发语言·leetcode·swift
leluckys3 小时前
swift-11-init、deinit、可选链、协议、元类型
开发语言·ios·swift
njsgcs3 小时前
vscode swift hello world
开发语言·ios·swift
Swift社区10 小时前
LeetCode 252 会议室题全解析:Swift 实现 + 场景还原
算法·leetcode·swift
phoenix16 小时前
Codable 宏让 Swift 序列化如此简单!
swift
leluckys1 天前
swift-08-属性、汇编分析inout本质
开发语言·汇编·swift
leluckys1 天前
swift-oc和swift block和代理
开发语言·ios·swift
leonyie20222 天前
7.3 在通知中显示图片或视频(UNNotificationAttachment)
macos·ios·swiftui·音视频·cocoa·swift
依旧风轻2 天前
使用 Swift 实现 LRU 缓存淘汰策略
缓存·swift·哈希表·lru·双向链表
Swift社区2 天前
Swift 解 LeetCode 250:搞懂同值子树,用递归写出权限系统检查器
开发语言·leetcode·swift