Detail the data type type conversion in Swift

  • 2020-05-17 06:37:52
  • OfStack

1. Type checking and conversion

In Objective-C and Java, any instance of a type can be forced to the compiler to think it is an instance of another type, essentially leaving all the security checking to the developer. By comparison, Optional conversions in Swift are safe and reliable.

The Swift keyword is is used for type checking, which returns a Boolean value true or false to indicate whether the check is valid, as shown below:


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

Swift has a feature of up compatibility and down conversion, that is, a collection of a parent class type can receive instances of a subclass. Similarly, when using these instance variables, it can be converted down to a subclass type, as shown below:


// The custom 1 Class and its subclasses 
class MyClass {
  var name:String?
}

class MySubClassOne: MyClass {
  var count:Int?
}
class MySubClassTwo: MyClass {
  var isBiger:Bool?
}
// create 3 An instance 
var obj1 = MyClass()
obj1.name = "HS"
var obj2 = MySubClassOne()
obj2.count = 100
var obj3 = MySubClassTwo()
obj3.isBiger=true
// Places an instance in an array collection of its common parent type 
var array:[MyClass] = [obj1,obj2,obj3]
// To traverse the 
for var i in 0..<array.count {
  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.name!)
  }
}

One thing to note is that you can use as! Or as & # 63; Come on, as! Is a cast method that is used by developers to make sure the type is correct, if as! If the conversion is of the wrong type, a runtime error occurs. as & # 63; Is the Optional type conversion, and if the conversion fails, nil is returned.

2. Any and AnyObject types

In Objective-C, id is often used to represent generics of reference types, similar to AnyObject in Swift. Here's an example:


// To traverse the 
for var i in 0..<array.count {
  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, and it can mix value type and reference type 1 to work, as shown below:


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

The array in the example above contains integers, string types, reference types, Boolean types, and closures.


Related articles: