SoFunction
Updated on 2025-04-09

Detailed explanation of data type conversion in Swift

1. Type checking and conversion

In Objective-C and Java, any type of instance can be forced to make the compiler think that it is another type of instance. This is actually to leave all the security checks to the developer himself. In comparison, Optional type conversion in Swift will be safer and more reliable.

Swift uses the is keyword to check the type, which will return a boolean value true or false to indicate whether the check is true. The example is as follows:

var str = "HS"
if str is String {
  print(str)
}

Swift has upward compatibility and down conversion features, that is, a collection of parent class types can receive instances of subclasses. Similarly, when using these instance variables, they can be downconverted to subclass types. The example is as follows:

//Customize a class and its subclassesclass MyClass {
  var name:String?
}

class MySubClassOne: MyClass {
  var count:Int?
}
class MySubClassTwo: MyClass {
  var isBiger:Bool?
}
//Create 3 instancesvar obj1 = MyClass()
 = "HS"
var obj2 = MySubClassOne()
 = 100
var obj3 = MySubClassTwo()
=true
//Storing instances in an array collection of its public parent class typevar array:[MyClass] = [obj1,obj2,obj3]
//Travel overfor var i in 0..< {
  var obj = array[i]
  if obj is MySubClassOne {
    print((obj as! MySubClassOne).count!)
    continue
  }
  if obj is MySubClassTwo {
    print((obj as! MySubClassTwo).isBiger!)
    continue
  }
  if obj is MyClass {
    print(!)
  }
}

One thing to note is that when performing type conversion, you can use as! or as?. As! is a cast method. It is used when the developer determines that the type is correct. If the type converted with as! is incorrect, a runtime error will occur. as? is an Optional type conversion, and if the conversion fails, nil will be returned.

2. Any and AnyObject types

In Objective-C, id is often used to represent generics of reference types, and AnyObject in Swift is similar to this. Examples are as follows:

//Travel overfor var i in 0..< {
  var obj = array[i]
  if obj is MySubClassOne {
    print((obj as! MySubClassOne).count!)
    continue
  }
  if obj is MySubClassTwo {
    print((obj as! MySubClassTwo).isBiger!)
    continue
  }
  if obj is MyClass {
    print((obj as! MyClass).name!)
  }
}

The Any type is more powerful than the AnyOject type, which can work with a mixture of value types and reference types. The examples are as follows:

var anyArray:[Any] = [100,"HS",obj1,obj2,false,(1.1),obj3,{()->() in print("Closures")}]

The array example above contains integers, string types, reference types, boolean types, and closures.