Typecasting or initialization, which is better in Swift?

后端 未结 1 461
清歌不尽
清歌不尽 2021-01-07 10:32

Since Swift does a strict check for types, sometimes we need to convert between NSString and String, NSArray and [AnyObject], etc. But in fact there are two different ways t

1条回答
  •  借酒劲吻你
    2021-01-07 11:13

    You are talking about casting vs. coercion. It isn't a matter of "recommended". They are completely different things.

    • Casting is merely a way of redescribing something to the compiler. Your redescription must be true already, or you will crash at runtime.

      For example, you can cast an AnyObject to a String (with as!) just in case it is a string; you are simply telling the compiler about this, so that you can then send String-related messages to this object. The cast is legal because String is bridged to NSString and an NSString is an AnyObject, so this AnyObject might indeed be a String. But if you lie and this is not a string, you'll crash later when the app runs and you try to cast to a String something that is not in fact already a String.

    • Coercion makes a new object entirely. It works only just in case the new type has an initializer that accepts the old object.

      For example, you cannot cast between numeric types in Swift. You have to coerce, which is a completely different thing - that is, you must make a new object of a different numeric type, based on the original object. The only way to use an Int8 where a UInt8 is expected is to coerce it: UInt8(x). And this is legal because UInt8 has an Int8 initializer (as you can see in the Swift header):

      extension UInt8 {
          public init(_ v: Int8)
          // ...
      }
      

    0 讨论(0)
提交回复
热议问题