swift – 泛型类型`UnsafeMutablePointer`的扩展

前端之家收集整理的这篇文章主要介绍了swift – 泛型类型`UnsafeMutablePointer`的扩展前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想为UnsafeMutablePointer创建一个只影响UnsafeMutablePointer< UInt8> …的扩展程序.

我理解这些说明是相关的,但我不确定如何:

When you extend a generic type,you do not provide a type parameter list as part of the extension’s definition. Instead,the type parameter list from the original type definition is available within the body of the extension,and the original type parameter names are used to refer to the type parameters from the original definition.

基本上,我正在尝试使用此方法

func toSwift(length: Int) -> [Int] {
    var retVal : [Int] = []
    for i in 0..<length {
        retVal.append(Int(self[i]))
    }
    return retVal
}

在没有UnsafeMutablePointer< UInt8>的情况下对自己采取行动作为参数……这可能吗?

Swift 3.1更新

从Swift 3.1(Xcode 8.3 beta版本)开始,现在支持具体的相同类型要求.你现在可以说:

extension UnsafeMutablePointer where Pointee == UInt8 {
    func asArray(withLength length: Int) -> [Int] {
        return UnsafeBufferPointer(start: self,count: length).map(Int.init)
    }
}

Pre Swift 3.1

你可以这样做 – 虽然它不是特别好.您必须创建一个新协议才能“标记”UInt8类型,然后将扩展约束到该协议.它也不允许您轻松指定Int(…)初始化程序可以采用_UInt8Type输入 – 您必须实现一个hacky’shadow’方法来执行此操作.

protocol _UInt8Type {
    func _asInt() -> Int
}
extension UInt8 : _UInt8Type {
    func _asInt() -> Int {
        return Int(self)
    }
}

// Change 'Pointee' to 'Memory' for Swift 2
extension UnsafeMutablePointer where Pointee : _UInt8Type {
    func asArray(withLength length:Int) -> [Int] {
        return UnsafeBufferPointer(start: self,count: length).map{$0._asInt()}
    }
}

总而言之,我更喜欢保持这个完全通用,并使用@AMomchilov’s solution.我只是为了完成而添加这个.

虽然值得注意的是,as a part of the Swift Generics Manifesto已经提出了具有扩展的具体相同类型要求(扩展类型,其中Generic == SomeType) – 所以希望这将在未来版本的Swift中实现.

猜你在找的Swift相关文章