Swift 等价于[NSBundle bundleForClass:[self class]]

2019-07-11 10:54:27 +08:00
 maxCham

什么是 swift 相当于下一个代码:[NSBundle bundleForClass:[self class]] ?

目前只知道 Swift = 2.x NSBundle(forClass: self.dynamicType) Swift 3.x Bundle(for: type(of: self))

但是 Swift4 之后要怎么写呢?请教各位 iOS 大神

4610 次点击
所在节点    iOS
13 条回复
jameskuk
2019-07-11 11:02:38 +08:00
你写的 swift3 的 Bundle(for: type(of: self)) 不能再 swift4 上用了吗?
maxCham
2019-07-11 11:05:03 +08:00
不能了
jameskuk
2019-07-11 11:10:19 +08:00
那你试试 Bundle(for: self.classForCoder())
maxCham
2019-07-11 11:10:40 +08:00
我的 type 系一个自定的类型,swift3 时这样写没问题;转 swift4 时就会报这个 type 是 Cannot call value of non-function type
maxCham
2019-07-11 11:12:30 +08:00
Bundle(for: self.classForCoder()) 这个肯定对,因为传进去的就是要 anyClass; 但是既然是 anyClass,为什么我这个自定义的 type 就不行了呢?
maxCham
2019-07-11 11:13:47 +08:00
我的 type 也是这样的一个 class 来的:class var typeList: DisplayType {}
maxCham
2019-07-11 11:14:56 +08:00
public enum DisplayType {
}
public final class Display {
class var typeList: DisplayType {
}
}
maxCham
2019-07-11 11:16:12 +08:00
let type = Display. typeList
let bundle = Bundle(for: type(of: self))
就会有错
momocraft
2019-07-11 11:16:41 +08:00
这个帖子第一行是英文机翻出来的吗?
finab
2019-07-11 11:21:12 +08:00
AnyClass 其实是 AnyObject.Type

如果你要把 typeList 当做 AnyClass
你需要这样定义
var typeList: DisplayType.Type
maxCham
2019-07-11 11:21:59 +08:00
哈哈,不是不是,只是搜索到一个帖子的标题,内容都是一样的,所以走来 V 站问问大神,交流交流
maxCham
2019-07-11 11:29:54 +08:00
谢谢大神们,我找到了,原来不是语法问题;是我理解错了,用会 Bundle(for: self.classForCoder())就可以了
onevcat
2019-07-11 12:30:25 +08:00
大概这样就行了?

Bundle(for: Self.self)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/581937

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX