Search code examples
arraysswift5

Why (Array<Character> = []) is Array<Bool> == true


If the defined array is empty, why the data type inside the array does not work

I create a empty Character Array, and I confused that why the result of a is Array<Bool> is true.

In fact, i tried a is Array<T> (T: Bool, String, Int...), all of them is true.

var a: Array<Character> = []

a is Array<Bool>

The result is:

true

Solution

  • After some digging, I found that this is the intended behavior.

    Swift checks whether an array can be downcast by attempting to downcast all of the source elements to the destination element type. Since an empty array contains no elements, that means down casting it to another array with a different element type is always successful.

    Below are swift's code for handling the as? operator. I doubt that swift handles the is operator differently.

    public func _arrayConditionalCast<SourceElement, TargetElement>(
      _ source: [SourceElement]
    ) -> [TargetElement]? {
      var successfulCasts = ContiguousArray<TargetElement>()
      successfulCasts.reserveCapacity(source.count)
      for element in source {
        if let casted = element as? TargetElement {
          successfulCasts.append(casted)
        } else {
          return nil
        }
      }
      return Array(successfulCasts)
    }
    
    

    https://github.com/apple/swift/blob/main/stdlib/public/core/ArrayCast.swift (line 74)

    Sources

    A similar bug report an swift.org: SR-7738

    Some convincing explanation: SR-6192