搜索

首页  >  问答  >  正文

ios - swift 里的类型判断问题?

swift 升级到 3.1 后遇到了警告,initialize() 将会在未来废弃,我在 stackoverflow 上找到了一个让人印象深刻的讨论,但在实践中的遇到了一些问题:

具体的代码如下,有兴趣的可以在 playground 跑一下,问题在注释里:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

<code class="swift">protocol Conscious {

    static func awake()

}

 

/** extension */

extension UIViewController: Conscious {

    static func awake() { 

        if self == UIViewController.self {  // 这里每个 UIViewController 的子类都调用了

            print(self, #function)          // 这里从没被调用

        }

    }

}

 

/** main */

private static let _operation: Void = {

    let typeCount = Int(objc_getClassList(nil, 0))

    let types = UnsafeMutablePointer<AnyClass?>.allocate(capacity: typeCount)

    let autoreleasingTypes = AutoreleasingUnsafeMutablePointer<AnyClass?>(types)

    objc_getClassList(autoreleasingTypes, Int32(typeCount))

 

    for index in 0 ..< typeCount {

        (types[index] as? Conscious.Type)?.awake()

         

        if let t = types[index] as? Conscious.Type {

            print(t)  // 所有 UIViewController 的子类都打印了,它自己没有被打印

        }

 

        let T = types[index]!

        let vc = UIViewController()

        print(T, vc.isKind(of: T), T == UIViewController.self)

        /*

          奇怪的打印:

          UIResponder true false

          UIViewController true false(why is false)

          UISearchController false false

         */

    }

 

    types.deallocate(capacity: typeCount)

}()</code>

大家讲道理大家讲道理2898 天前814

全部回复(0)我来回复

暂无回复
  • 取消回复