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...

相关推荐
幸福回头17 小时前
ms-swift 代码推理数据集
llm·swift
不二狗1 天前
每日算法 -【Swift 算法】Two Sum 问题:从暴力解法到最优解法的演进
开发语言·算法·swift
struggle20253 天前
适用于 iOS 的 开源Ultralytics YOLO:应用程序和 Swift 软件包,用于在您自己的 iOS 应用程序中运行 YOLO
yolo·ios·开源·app·swift
一丝晨光4 天前
数值溢出保护?数值溢出应该是多少?Swift如何让整数计算溢出不抛出异常?类型最大值和最小值?
java·javascript·c++·rust·go·c·swift
Swift社区4 天前
Swift实战:如何优雅地从二叉搜索树中挑出最接近的K个值
开发语言·ios·swift
fydw_7154 天前
大语言模型RLHF训练框架全景解析:OpenRLHF、verl、LLaMA-Factory与SWIFT深度对比
语言模型·swift·llama
文件夹__iOS4 天前
深入浅出 iOS 对象模型:isa 指针 与 Swift Metadata
ios·swift
I烟雨云渊T6 天前
iOS实名认证模块的具体实现过程(swift)
ios·cocoa·swift
Swift社区6 天前
LeetCode 270:在二叉搜索树中寻找最接近的值(Swift 实战解析)
算法·leetcode·swift
I烟雨云渊T7 天前
iOS瀑布流布局的实现(swift)
开发语言·ios·swift