Den*_*eny 2 generics inheritance ios swift
这两个函数声明之间有区别吗?
func doSomething<T: UIViewController>(controller: T) {...}
Run Code Online (Sandbox Code Playgroud)
与
func doSomething(controller: UIViewController) {...}
Run Code Online (Sandbox Code Playgroud)
在Apples Swift编程语言书的Type Constraint Syntax部分中,有以下代码示例:
func? ?someFunction?<?T?: ?SomeClass?, ?U?: ?SomeProtocol?>(?someT?: ?T?, ?someU?: ?U?) {
// function body goes here
}
Run Code Online (Sandbox Code Playgroud)
有了这个描述:
上面的假设函数有两个类型参数.第一个类型参数T有一个类型约束,要求T是SomeClass的子类....
那么在哪种情况下使用上述通用功能会更好?
它们是不同的,但在你使用它们的方式中,它们几乎完全相同.
不同之处在于,当您调用泛型版本时,编译器会T静态设置为作为参数传入的任何类型.在对该参数调用方法时,这几乎没有区别 - 无论是对方法的调用都将动态调度,并且T不能保证可以从约束中获得的任何部分.
但是假设您对此方法进行了更改,不仅仅是接受一个参数,而且还返回一个相同类型的参数:
// T here will take the type of whatever is going in/out of the function
// be that UIViewController or a subtype of it
func doSomethingGenerically<T: UIViewController>(controller: T) -> T {
// some logic that results in a new controller being returned
}
// here the return type is fixed to be UIViewController
func doSomethingViaBaseClass(controller: UIViewController) -> UIViewController {
// some logic that results in a new controller being returned
}
Run Code Online (Sandbox Code Playgroud)
现在,假设您有一个UIViewController传入的子类,如下所示:
let subClass: MyUIViewController = ...
let controller1 = doSomethingGenerically(subClass)
let controller2 = doSomethingViaBaseClass(subClass)
Run Code Online (Sandbox Code Playgroud)
这里,变量的类型controller1将是MyUIViewController,因为这是传递给函数的内容,因此就是这样T.但变量的类型controller2将是UIViewController因为这是doSomethingViaBaseClass返回的固定类型.
注意,这并不意味着它们引用的对象会有所不同 - 这取决于函数体的实现方式.只是引用它的变量类型会发生变化.
还有其他微妙的差异,但这是最需要了解的.然而,就结构而言,还有更多的差异需要注意.碰巧我昨天写了一篇关于他们的文章可能有所帮助.
| 归档时间: |
|
| 查看次数: |
328 次 |
| 最近记录: |