启用Swift编译器优化时,我遇到了不同的结果。
这是因为我需要检查传递给泛型函数的对象是否是类类型(因此我可以存储weak
引用。)
如果没有优化,type(of:)
报告的传递给doSomething
的值的类型是正确的类(AppDelegate
)。但是,如果启用了优化,则会将类型报告为泛型类型(在本例中为Barable
)。所以我检查对象是否是一个类isClass
与各种优化级别不同。
这是错误还是预期的行为?
import UIKit
class Foo<T> {
func doSomething(value: T) {
print(type(of: value))
let isClass = type(of: value) is AnyClass
print(isClass)
// Swift Compiler Optimisation: None
// - type(of: value) == AppDelegate
// - isClass = true
// Swift Compiler Optimisation: Single File Optimisation
// - type(of: value) == Barable
// - isClass = false
}
}
protocol Barable { }
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, Barable {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let foos = Foo<Barable>()
foos.doSomething(value: self)
return true
}
}