gpt4 book ai didi

swift - 在 swift 中向特定类型的数组添加自定义 init 方法

转载 作者:搜寻专家 更新时间:2023-11-01 05:36:29 27 4
gpt4 key购买 nike

我想使用扩展快速将自定义 init 方法添加到 Array 类,但关键是我只想将它添加到字节数组 (UInt8)

我目前有这样的东西:

public class MyData {
}

public func toByteArray(myData: MyData) -> [UInt8]? { // a global function
// code to check if myData is valid, and extract byte array
}

似乎更“swift ”的做法是使用可失败的初始化器,所以我想这样写

extension Array where Element : UInt8 {
init?(myData: MyData) {
// code to check if myData is valid, and extract byte array
}
}

虽然这段代码无法编译,但我得到 Type 'Element' constrained to a non-protocol type 'UInt8'

我找到了 other things在你不扩展 Array 的地方,你改为扩展 _ArrayType,但这似乎不适用于初始化器

最佳答案

在 Swift 2.2 中实现这一点的唯一方法是制定一个 UInt8 符合的协议(protocol),并将其作为约束用于 Array 扩展。

protocol UInt8Protocol {}
extension UInt8 : UInt8Protocol {}

extension Array where Element : UInt8Protocol {

init?(myData: MyData) {
...
}
}

在 Swift 进化列表中提到,这个(使用相同类型约束的约束扩展)是一个非常需要的特性。它可能是下一版 Swift 的一部分。

关于swift - 在 swift 中向特定类型的数组添加自定义 init 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38192396/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com