gpt4 book ai didi

swift - 为什么这有效? Swift(UnsafeMutablePointer<可选>)

转载 作者:行者123 更新时间:2023-11-30 13:36:18 27 4
gpt4 key购买 nike

protocol Property {}
protocol OptionalProtpery : Property {
static func codeNilInto(pointer: UnsafePointer<Int>)
}

extension Optional : OptionalProtpery {
static func codeNilInto(pointer: UnsafePointer<Int>) {
(UnsafeMutablePointer(pointer) as UnsafeMutablePointer<Optional>).memory = nil
}
}

我对此声明感兴趣 UnsafeMutablePointer<"Optional">为什么我们没有错误,例如:“可选泛型类型并且需要参数 <...>”。由于此处未指定特定类型(例如 UnsafeMutablePointer<"Optional"<"Int">>)。

最佳答案

protocol Property {}
protocol OptionalProtpery : Property {
static func codeNilInto(pointer: UnsafePointer<Int>)
}

extension Optional : OptionalProtpery {
static func codeNilInto(pointer: UnsafePointer<Int>) {
(UnsafeMutablePointer(pointer) as UnsafeMutablePointer<Optional>).memory = nil
}
}

var i = 1
let p = withUnsafePointer(&i) { (p) -> UnsafePointer<Int> in
return p
}
print(p.memory) // 1

//Optional.codeNilInto(p) // error: generic parameter 'Wrapped' could not be inferred
// you have to specify generic parameter !!!
Optional<Int>.codeNilInto(p)
Optional<Double>.codeNilIntro(p)
// or what ever you want to express

所以,因为Optional是通用的,所以你的代码是“OK”。顺便问一下,您希望您的代码做什么?

关于swift - 为什么这有效? Swift(UnsafeMutablePointer<可选>),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36032818/

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