xcode .dynamicType 已弃用。使用'type(of ...)'代替
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39495021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.dynamicType is deprecated. Use 'type(of ...)' instead
提问by Rodrigo
I've just updated to Xcode 8 and iOS 10 (using legacy Swift Language Version).
我刚刚更新到 Xcode 8 和 iOS 10(使用旧的 Swift 语言版本)。
Trying to compile again my project has been an agony, even still using the old Swift syntax. This time one of my functions uses NSBundle(forClass: self.dynamicType)
but now appears that .dynamicType
is deprecated and Xcode doesn't even want to compile it.
尝试再次编译我的项目一直很痛苦,即使仍然使用旧的 Swift 语法。这次我的一个函数使用NSBundle(forClass: self.dynamicType)
但现在似乎.dynamicType
已弃用,Xcode 甚至不想编译它。
His suggestion is to use type(of: self)
but that fails as well. Anyone knows the solution? Thanks.
他的建议是使用,type(of: self)
但这也失败了。有谁知道解决方案?谢谢。
采纳答案by Rodrigo
@dfri answer works perfectly for Swift 3.
@dfri 答案非常适合 Swift 3。
Regarding Swift 2.3, my solution was to clean Xcode (Command+Option+Shift+K) and delete everything in ~/Library/Developer/Xcode/DerivedData
. The problem doesn't disappear instantly but after some time it will stop giving that error.
关于 Swift 2.3,我的解决方案是清理 Xcode (Command+Option+Shift+K) 并删除~/Library/Developer/Xcode/DerivedData
. 问题不会立即消失,但一段时间后它会停止给出该错误。
Maybe it's a bug, after all we are in 8.0. I hope it gets fixed in next releases.
也许这是一个错误,毕竟我们是在 8.0 中。我希望它在下一个版本中得到修复。
Thank you everyone.
谢谢大家。
回答by dfri
(The below holds for Swift 3; not legacy Swift Language Version (2.3), however, so it doesn't answer the OP's question, but could be valuable for Swift 3 users, nonetheless)
(以下适用于 Swift 3;但不是旧的 Swift 语言版本 (2.3),因此它没有回答 OP 的问题,但对于 Swift 3 用户来说可能很有价值)
As noted in your question, dynamicType
is now (Swift 3) deprecated in favour of type(of:)
. In addition:
正如您在问题中所指出的,dynamicType
现在(Swift 3)已被弃用而支持type(of:)
. 此外:
NSBundle
has been renamed toBundle
.- The
init(forClass:)
initializer ofBundle
has been renamed toinit(for:)
.
NSBundle
已更名为Bundle
.- 的
init(forClass:)
初始值设定项Bundle
已重命名为init(for:)
.
Taking these changes into account, For Swift 3 you initialize (or fetch an existing instance associated with the specific class) your Bundle
object in the following manner:
考虑到这些更改,对于 Swift 3,您可以Bundle
通过以下方式初始化(或获取与特定类关联的现有实例)您的对象:
class Foo {
func bar() -> () {
let bundle = Bundle(for: type(of: self))
// ...
}
}