Swift type conversion


Release date:2023-12-06 Update date:2023-12-11 Editor:admin View counts:189

Label:

Swift type conversion

Swift language type conversion can determine the type of instance. It can also be used to detect whether an instance type belongs to an instance of its parent or subclass.

Type conversion is used in Swift is and a s operator implementation is the type used to detect the value as used to convert types.

Type conversion can also be used to check whether a class implements a protocol.

Define a class hierarchy

Three classes are defined below: SubjectsChemistry , Maths , Chemistry and Maths inherited Subjects .

The code is as follows:

class Subjects {
    var physics: String
    init(physics: String) {
        self.physics = physics
    }
}

class Chemistry: Subjects {
    var equations: String
    init(physics: String, equations: String) {
        self.equations = equations
        super.init(physics: physics)
    }
}

class Maths: Subjects {
    var formulae: String
    init(physics: String, formulae: String) {
        self.formulae = formulae
        super.init(physics: physics)
    }
}

let sa = [
    Chemistry(physics: "solid state physics", equations: "hertz"),
    Maths(physics: "fluid dynamics", formulae: "GHz")]


let samplechem = Chemistry(physics: "solid state physics", equations: "hertz")
print("Example physics is: \(samplechem.physics)")
print("Instance equation: \(samplechem.equations)")


let samplemaths = Maths(physics: "fluid dynamics", formulae: "GHz")
print("Example physics is: \(samplemaths.physics)")
print("The example formula is: \(samplemaths.formulae)")

The output of the above program execution is as follows:

Example physics is: solid state physics
Example equation: Hertz
Example physics is fluid dynamics
The example formula is: GHz

Check type

Type conversion is used to detect whether an instance type belongs to a specific instance type.

You can use it on the hierarchy of classes and subclasses, checking the typeof a particular class instance and converting the type of that class instance to other types in the hierarchy.

Type check use is keyword.

Operator is to check whether an instance belongs to a specific subtype. If the instance belongs to that subtype, the type checking operator returns true otherwise, return false .

class Subjects {
    var physics: String
    init(physics: String) {
        self.physics = physics
    }
}

class Chemistry: Subjects {
    var equations: String
    init(physics: String, equations: String) {
        self.equations = equations
        super.init(physics: physics)
    }
}

class Maths: Subjects {
    var formulae: String
    init(physics: String, formulae: String) {
        self.formulae = formulae
        super.init(physics: physics)
    }
}

let sa = [
    Chemistry(physics: "Solid State Physics", equations: "hertz"),
    Maths(physics: "fluid dynamics", formulae: "Gigahertz"),
    Chemistry(physics: "Thermophysics", equations: "Decibel"),
    Maths(physics: "Astrophysics", formulae: "Megahertz"),
    Maths(physics: "differential equation", formulae: "Cosine series")]


let samplechem = Chemistry(physics: "Solid State Physics", equations: "hertz")
print("Example physics is: \(samplechem.physics)")
print("Instance equation: \(samplechem.equations)")


let samplemaths = Maths(physics: "fluid dynamics", formulae: "Gigahertz")
print("Example physics is: \(samplemaths.physics)")
print("Instance equation: \(samplemaths.formulae)")

var chemCount = 0
var mathsCount = 0
for item in sa {
    // If it is an instance of type Chemistry, return true, otherwise return false.
    if item is Chemistry {
        ++chemCount
    } else if item is Maths {
        ++mathsCount
    }
}

print("The chemistry subject includes \(chemCount) several topics,Mathematics contains \(mathsCount) several topics")

The output of the above program execution is as follows:

Example physics is: solid state physics
Example equation: Hertz
Example physics is fluid dynamics
The example formula is: GHz
The chemistry subject contains 2 topics, while mathematics contains 3 topics

Downward transformation

Transition down, with the type conversion operator as? or as! )

When you are not sure that the downward transformation will be successful, use the conditional form of type conversion as? ). Conditional type conversions always return an optional value (optional value and if downloading is not possible, the optional value will be nil .

Use the coercive form only if you are sure that the downward transition willbe successful ( as! ). When you try to convert down to an incorrect type, a forced form of type conversion triggers a run-time error.

class Subjects {
    var physics: String
    init(physics: String) {
        self.physics = physics
    }
}

class Chemistry: Subjects {
    var equations: String
    init(physics: String, equations: String) {
        self.equations = equations
        super.init(physics: physics)
    }
}

class Maths: Subjects {
    var formulae: String
    init(physics: String, formulae: String) {
        self.formulae = formulae
        super.init(physics: physics)
    }
}

let sa = [
    Chemistry (physics: "Solid State Physics", equations: "Hertz"),
    Maths (physics: "fluid dynamics", formula: "gigahertz"),
    Chemistry (physics: "thermophysics", equations: "decibels"),
    Maths (physics: "Astrophysics", formula: "Megahertz"),
    Maths (physics: "differential equations", formula: "cosine series")]


 Let sampler=Chemistry (physics: "Solid State Physics", equations: "Hertz")
 Print ("Example physics is: \ (samplechem. physics)")
 Print ("Example Equation: \ (samplechem. equations)")


 Let samples=Mathematics (physics: "fluid dynamics", formula: "gigahertz")
 Print ("Example physics is: \ (samples. physics)")
 Print ("The instance formula is: \ (samples. formula)")

var chemCount = 0
var mathsCount = 0

for item in sa {
    // The conditional form of type conversion
    if let show = item as? Chemistry {
        print("The theme of chemistry is: '\(show.physics)', \(show.equations)")
        // Compulsory form
    } else if let example = item as? Maths {
        print("The mathematical theme is: '\(example.physics)',  \(example.formulae)")
    }
}

The output of the above program execution is as follows:

Example physics is: solid state physics
Example equation: Hertz
Example physics is fluid dynamics
The example formula is: GHz
The chemistry theme is: 'Solid State Physics', Hertz
The mathematical theme is: 'Fluid dynamics', gigahertz
The chemistry theme is: 'Thermophysics', decibels
The mathematical theme is: 'Astrophysics', megahertz
The mathematical theme is: 'Differential equations', cosine series

Any and AnyObject type conversion

Swift provides two special type aliases for uncertain types:

  • AnyObject can represent any class an instance of the type.

  • Any can represent any type, including the method type (function types).

Note: use it only if you explicitly need its behavior and functionality. Any and AnyObject . It is always better to use the specific type you expect in your code.

Any instance

class Subjects {
    var physics: String
    init(physics: String) {
        self.physics = physics
    }
}

class Chemistry: Subjects {
    var equations: String
    init(physics: String, equations: String) {
        self.equations = equations
        super.init(physics: physics)
    }
}

class Maths: Subjects {
    var formulae: String
    init(physics: String, formulae: String) {
        self.formulae = formulae
        super.init(physics: physics)
    }
}

let sa = [
Chemistry (physics: "Solid State Physics", equations: "Hertz"),
Maths (physics: "fluid dynamics", formula: "gigahertz"),
Chemistry (physics: "thermophysics", equations: "decibels"),
Maths (physics: "Astrophysics", formula: "Megahertz"),
Maths (physics: "differential equations", formula: "cosine series")

Let sampler=Chemistry (physics: "Solid State Physics", equations: "Hertz")
Print ("Example physics is: \ (samplechem. physics)")
Print ("Example Equation: \ (samplechem. equations)")


Let samples=Mathematics (physics: "fluid dynamics", formula: "gigahertz")
Print ("Example physics is: \ (samples. physics)")
Print ("The instance formula is: \ (samples. formula)")

var chemCount = 0
var mathsCount = 0

for item in sa {
    // The conditional form of type conversion
    if let show = item as? Chemistry {
        print("The theme of chemistry is: '\(show.physics)', \(show.equations)")
        // Compulsory form
    } else if let example = item as? Maths {
        print("The mathematical theme is: '\(example.physics)',  \(example.formulae)")
    }
}

// Can store arrays of type Any exampleany
var exampleany = [Any]()

exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Any example")
exampleany.append(Chemistry(physics: "solid state physics", equations: "megahertz"))

for item2 in exampleany {
    switch item2 {
    case let someInt as Int:
        print("The integer value is \(someInt)")
    case let someDouble as Double where someDouble > 0:
        print("The Pi value is \(someDouble)")
    case let someString as String:
        print("\(someString)")
    case let phy as Chemistry:
        print("theme '\(phy.physics)', \(phy.equations)")
    default:
        print("None")
    }
}

The output of the above program execution is as follows:

Example physics is: solid state physics
Example equation: Hertz
Example physics is fluid dynamics
The example formula is: GHz
The chemistry theme is: 'Solid State Physics', Hertz
The mathematical theme is: 'Fluid dynamics', gigahertz
The chemistry theme is: 'Thermophysics', decibels
The mathematical theme is: 'Astrophysics', megahertz
The mathematical theme is: 'Differential equations', cosine series
The integer value is 12
The Pi value is 3.14159
Any instance
Theme 'Solid State Physics', MHz

AnyObject Example

class Subjects {
    var physics: String
    init(physics: String) {
        self.physics = physics
    }
}

class Chemistry: Subjects {
    var equations: String
    init(physics: String, equations: String) {
        self.equations = equations
        super.init(physics: physics)
    }
}

class Maths: Subjects {
    var formulae: String
    init(physics: String, formulae: String) {
        self.formulae = formulae
        super.init(physics: physics)
    }
}

// [AnyObject] Array of types
let saprint: [AnyObject] = [
Chemistry (physics: "Solid State Physics", equations: "Hertz"),
Maths (physics: "fluid dynamics", formula: "gigahertz"),
Chemistry (physics: "thermophysics", equations: "decibels"),
Maths (physics: "Astrophysics", formula: "Megahertz"),
Maths (physics: "differential equations", formula: "cosine series")


 Let sampler=Chemistry (physics: "Solid State Physics", equations: "Hertz")
 Print ("Example physics is: \ (samplechem. physics)")
 Print ("Example Equation: \ (samplechem. equations)")


 Let samples=Mathematics (physics: "fluid dynamics", formula: "gigahertz")
 Print ("Example physics is: \ (samples. physics)")
 Print ("The instance formula is: \ (samples. formula)")

var chemCount = 0
var mathsCount = 0

for item in saprint {
    // The conditional form of type conversion
    if let show = item as? Chemistry {
        print("The theme of chemistry is: '\(show.physics)', \(show.equations)")
        // Compulsory form
    } else if let example = item as? Maths {
        print("The mathematical theme is: '\(example.physics)',  \(example.formulae)")
    }
}

var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Any example")
exampleany.append(Chemistry(physics: "solid state physics", equations: "megahertz"))

for item2 in exampleany {
    switch item2 {
    case let someInt as Int:
        print("The integer value is\(someInt)")
    case let someDouble as Double where someDouble > 0:
        print("The Pi value is \(someDouble)")
    case let someString as String:
        print("\(someString)")
    case let phy as Chemistry:
        print("theme '\(phy.physics)', \(phy.equations)")
    default:
        print("None")
    }
}

The output of the above program execution is as follows:

Example physics is: solid state physics
Example equation: Hertz
Example physics is fluid dynamics
The example formula is: GHz
The chemistry theme is: 'Solid State Physics', Hertz
The mathematical theme is: 'Fluid dynamics', gigahertz
The chemistry theme is: 'Thermophysics', decibels
The mathematical theme is: 'Astrophysics', megahertz
The mathematical theme is: 'Differential equations', cosine series
The integer value is 12
The Pi value is 3.14159
Any instance
Theme 'Solid State Physics', MHz

In a switch statement case type conversion operators in the mandatory form are used in the as instead of as? to check and convert to an explicit type

Powered by TorCMS (https://github.com/bukun/TorCMS).