V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
maxCham
V2EX  ›  iOS

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

  •  
  •   maxCham · 2019-07-11 10:54:27 +08:00 · 4578 次点击
    这是一个创建于 1722 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

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

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

    Bundle(for: Self.self)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3116 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:30 · PVG 22:30 · LAX 07:30 · JFK 10:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.