具有由初始化程序决定的泛型类型的不安全可变指针参数的类(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) } }更多推荐
发布评论