- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我正在尝试在 Swift、Xcode 7.3(所以是 Swift 2.2)中创建一个通用类,但我似乎无法让它通过编译器:
protocol Struct1Protocol {
}
struct Struct1 {
var name1: String
}
protocol Struct2Protocol {
}
struct Struct2: Struct2Protocol {
var name2: String
}
class StructDependent<T> {
func setupFrom<T:Struct1Protocol>(value: T) {
print("we want to setup StructDependent with struct 1")
}
func setupFrom<T:Struct2Protocol>(value: T) {
print("we want to setup StructDependent with struct 2")
}
}
class A<T> {
func test(value: T) {
let structInstance = StructDependent<T>()
// this gives a compiler error:
// Cannot invoke 'setupFrom' with an argument list of type '(T)'
structInstance.setupFrom(value)
}
}
想法是拥有一个可以从不同结构设置的 StructDependent
。如果类已使用兼容结构实例化,则类 A 应该能够调用 setupFrom。像这样:
let a = A<Struct1>()
let v = Struct1(name1: "")
a.test(v)
我该怎么做?我在这里有点受阻,所以欢迎所有想法。
最佳答案
我觉得你想多了。我会以更简单的方式看待这个案例,完全不用泛型来做;相反,我们只是使用协议(protocol)作为两个结构的一种父类(super class)型(就像如果结构是类,我们将使用父类(super class)一样):
protocol StructProtocol {
var name : String {get set}
func setup()
}
struct Struct1 : StructProtocol{
var name: String
func setup() {}
}
struct Struct2 : StructProtocol {
var name: String
func setup() {}
}
class StructDependent {
func setup(s:StructProtocol) {
s.setup() // or not, I don't care...
// or you could just switch on the type, e.g.:
switch s {
case is Struct1: // ...
case is Struct2: // ...
default: break
}
}
}
class A {
func test(value: StructProtocol) {
let structInstance = StructDependent()
structInstance.setup(value)
}
}
如果 StructDependent 本身 确实需要根据调用 setup
的方式做不同的事情,它可以切换到实际类型。但第一种方式会更好,我们只调用 Struct1 和 Struct2 都知道如何做的东西,每个都以自己的方式。
关于swift - 试图 swift 概括,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37010947/
我是 C++ 的新手,我在使用这段代码时遇到了问题: string output_date(int day, int month, int year){ string date; if
所以我这样做了 tar cvzf test.zip FP 为了创建目录 FP 的 zip 但是,它会列出 zip 中的目录 FP/ FP/php/ FP/php/pdf/ FP/php/docs/ F
我正在尝试在 Swift、Xcode 7.3(所以是 Swift 2.2)中创建一个通用类,但我似乎无法让它通过编译器: protocol Struct1Protocol { } struct Str
我的测试用例是这样的: class FooTest extends PHPUnit_Framework_TestCase { /** @covers MyClass::bar */ f
我正在尝试将brew install wine作为使electron-builder工作的一步。但是我所能得到的只是以下响应: ==> Installing dependencies for wine
我这样做: string[,] string1 = {{"one", "0"},{"Two", "5"},{"Three","1"}}; int b = 0; for(int i = 0; i <=
我正在尝试使用 SetWindowsHookEx 键盘 Hook Notepad.exe。 如您所见,工作线程正在将其 ASCII 代码(即 wParam)发送到指定的服务器。 UINT WINAPI
我正在尝试将 ListView 实现到我的 Fragment 中,但无论我尝试什么,我都会得到一个 NullPointerException。我检查对象是否为 null 并记录是否为 null,看起来
我尝试在一行中对齐两个 div。使用 float left 属性,一切顺利。但是当我在 div 中使用图像时,它开始产生问题。 所以这是我的示例代码:- Some headi
我目前正在使用此代码来获取图像的灰度图像表示并以 (512, 370, 1) 的格式表示它大批。 img_instance = cv2.imread(df.iloc[i][x_col]) / 255.
总结 我正在创建一个简单的应用程序,它允许用户选择一个包含顶级窗口的进程。用户首先键入 native DLL(而非托管 DLL)的路径。然后用户键入将在 Hook 过程中调用的方法的名称。该方法不得返
我是一名优秀的程序员,十分优秀!