Are there any concrete examples when using the Any type is a good solution?

前端 未结 2 1160
甜味超标
甜味超标 2020-12-20 07:16

We all know that swift has a strong type system, and as such I lean towards using this system to my advantage :)

Here\'s what Apple has to say about using the Any t

2条回答
  •  清酒与你
    2020-12-20 07:54

    If you are using pure Swift (without the legacy Objective-C stuff) and you want an array where you can put Int(s), Bool(s) and String(s) then you need an array of Any.

    let values: [Any] = [1, true, "I'm not a pointer!"]
    

    But, wait I can also use an array of AnyObject right?

    Nope. Infact Int, Bool and String in Swift are struct(s).

    They why does this code compile?

    The code above compile because the import Foundation does enable the bridge to Objective-C. This mean the Swift Int, Bool and String are allowed to be seen as objects by the compiler in order to preserve compatibility with Objective-C.

    But as soon as you remove the import Foundation the code stop compiling.

提交回复
热议问题