具有由初始化程序决定的泛型类型的不安全可变指针参数的类(Class with unsafe mutable pointer parameter of generic type decided by t

编程入门 行业动态 更新时间:2024-10-28 02:26:14
具有由初始化程序决定的泛型类型的不安全可变指针参数的类(Class with unsafe mutable pointer parameter of generic type decided by the initializer)

我正在尝试创建一个基于其关联类型操作不同的类。 Apon初始化我将一个类型传递给初始化器以及一些未显示的其他参数。 我的困境是我要编写的以下代码,但由于编译器错误而无法编写。

class Foo { var data: UnsafeMutablePointer<T> var type: T.Type init?<T>(type: T.Type) { data = UnsafeMutablePointer<T> self.type = type } func prepareForData() { data = UnsafeMutableRawPointer(memoryAddress + variableOffset).bindMemory(to:type.self, capacity:1) } }

理论上如何使用类

let thing = Foo(Int)或者let thing2 = Foo(coolStruct)

这在Swift中甚至可能吗?

I am trying to create a class that operates differently based on its associated type. Apon initialization I will pass in a type to the initializer along with some other parameters not shown. My dilemma is the following bit of code I want to write but can't due to a compiler error.

class Foo { var data: UnsafeMutablePointer<T> var type: T.Type init?<T>(type: T.Type) { data = UnsafeMutablePointer<T> self.type = type } func prepareForData() { data = UnsafeMutableRawPointer(memoryAddress + variableOffset).bindMemory(to:type.self, capacity:1) } }

where the class would be theoretically used like

let thing = Foo(Int) or let thing2 = Foo(coolStruct)

Is this even possible in Swift?

最满意答案

无法检查自己,但以下应编译并正常工作:

class Foo<T> { var data: UnsafeMutablePointer<T> var type: T.Type init?(type: T.Type) { data = UnsafeMutablePointer<T>() self.type = type } func prepareForData() { data = UnsafeMutableRawPointer(memoryAddress + variableOffset).bindMemory(to:type.self, capacity:1) } }

Can not check myself but the following should compile and work properly:

class Foo<T> { var data: UnsafeMutablePointer<T> var type: T.Type init?(type: T.Type) { data = UnsafeMutablePointer<T>() self.type = type } func prepareForData() { data = UnsafeMutableRawPointer(memoryAddress + variableOffset).bindMemory(to:type.self, capacity:1) } }

更多推荐

本文发布于:2023-07-28 21:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1309446.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:初始化   指针   不安全   参数   类型

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!