Swift - Tipo Casting
Para validar el tipo de instancia, entra en juego 'Type Casting' en el idioma Swift 4. Se utiliza para comprobar si el tipo de instancia pertenece a una superclase o subclase en particular o si está definido en su propia jerarquía.
La conversión de tipo Swift 4 proporciona dos operadores 'es' para verificar el tipo de un valor y 'como' y para convertir el valor de tipo a un tipo diferente. La conversión de tipos también comprueba si el tipo de instancia sigue un estándar de conformidad de protocolo particular.
Definición de una jerarquía de clases
La conversión de tipos se utiliza para verificar el tipo de instancias y averiguar si pertenece a un tipo de clase en particular. Además, verifica la jerarquía de clases y sus subclases para verificar y convertir esas instancias para convertirlas en una misma jerarquía.
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 physics", equations: "Hertz"),
Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")]
let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")
let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")
Cuando ejecutamos el programa anterior usando el patio de recreo, obtenemos el siguiente resultado:
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Comprobación de tipo
La verificación de tipos se realiza con el operador 'es'. El operador de verificación de tipo 'es' comprueba si la instancia pertenece a un tipo de subclase en particular y devuelve 'verdadero' si pertenece a esa instancia; de lo contrario, devolverá 'falso'.
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 physics", equations: "Hertz"),
Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
Chemistry(physics: "Thermo physics", equations: "Decibels"),
Maths(physics: "Astro Physics", formulae: "MegaHertz"),
Maths(physics: "Differential Equations", formulae: "Cosine Series")]
let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")
let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
if item is Chemistry {
++chemCount
} else if item is Maths {
++mathsCount
}
}
print("Subjects in chemistry contains \(chemCount) topics and maths contains \(mathsCount) topics")
Cuando ejecutamos el programa anterior usando el patio de recreo, obtenemos el siguiente resultado:
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Subjects in chemistry contains 2 topics and maths contains 3 topics
Downcasting
Se puede reducir el tipo de subclase con dos operadores (como? Y como!). 'Como?' devuelve un valor opcional cuando el valor devuelve nulo. Se utiliza para comprobar el abatimiento exitoso.
'¡como!' devuelve desenvolvimiento forzado como se explica en el encadenamiento opcional cuando el abatimiento devuelve un valor nulo. Se utiliza para desencadenar un error de tiempo de ejecución en caso de falla abatida
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 physics", equations: "Hertz"),
Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
Chemistry(physics: "Thermo physics", equations: "Decibels"),
Maths(physics: "Astro Physics", formulae: "MegaHertz"),
Maths(physics: "Differential Equations", formulae: "Cosine Series")]
let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")
let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
if let print = item as? Chemistry {
print("Chemistry topics are: '\(print.physics)', \(print.equations)")
} else if let example = item as? Maths {
print("Maths topics are: '\(example.physics)', \(example.formulae)")
}
}
Cuando ejecutamos el programa anterior usando el patio de recreo, obtenemos el siguiente resultado:
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series
Encasillado: cualquier objeto
La palabra clave 'Cualquiera' se utiliza para representar una instancia que pertenece a cualquier tipo, incluidos los tipos de función.
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 physics", equations: "Hertz"),
Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
Chemistry(physics: "Thermo physics", equations: "Decibels"),
Maths(physics: "Astro Physics", formulae: "MegaHertz"),
Maths(physics: "Differential Equations", formulae: "Cosine Series")]
let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")
let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
if let print = item as? Chemistry {
print("Chemistry topics are: '\(print.physics)', \(print.equations)")
} else if let example = item as? Maths {
print("Maths topics are: '\(example.physics)', \(example.formulae)")
}
}
var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Example for Any")
exampleany.append(Chemistry(physics: "solid physics", equations: "Hertz"))
for print in exampleany {
switch print {
case let someInt as Int:
print("Integer value is \(someInt)")
case let someDouble as Double where someDouble > 0:
print("Pi value is \(someDouble)")
case let someString as String:
print("\(someString)")
case let phy as Chemistry:
print("Topics '\(phy.physics)', \(phy.equations)")
default:
print("None")
}
}
Cuando ejecutamos el programa anterior usando el patio de recreo, obtenemos el siguiente resultado:
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series
Integer value is 12
Pi value is 3.14159
Example for Any
Topics 'solid physics', Hertz
AnyObject
Para representar la instancia de cualquier tipo de clase, se utiliza la palabra clave 'AnyObject'.
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 saprint: [AnyObject] = [Chemistry(physics: "solid physics", equations: "Hertz"),
Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz"),
Chemistry(physics: "Thermo physics", equations: "Decibels"),
Maths(physics: "Astro Physics", formulae: "MegaHertz"),
Maths(physics: "Differential Equations", formulae: "Cosine Series")]
let samplechem = Chemistry(physics: "solid physics", equations: "Hertz")
print("Instance physics is: \(samplechem.physics)")
print("Instance equation is: \(samplechem.equations)")
let samplemaths = Maths(physics: "Fluid Dynamics", formulae: "Giga Hertz")
print("Instance physics is: \(samplemaths.physics)")
print("Instance formulae is: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in saprint {
if let print = item as? Chemistry {
print("Chemistry topics are: '\(print.physics)', \(print.equations)")
} else if let example = item as? Maths {
print("Maths topics are: '\(example.physics)', \(example.formulae)")
}
}
var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Example for Any")
exampleany.append(Chemistry(physics: "solid physics", equations: "Hertz"))
for print in exampleany {
switch print {
case let someInt as Int:
print("Integer value is \(someInt)")
case let someDouble as Double where someDouble > 0:
print("Pi value is \(someDouble)")
case let someString as String:
print("\(someString)")
case let phy as Chemistry:
print("Topics '\(phy.physics)', \(phy.equations)")
default:
print("None")
}
}
Cuando ejecutamos el programa anterior usando el patio de recreo, obtenemos el siguiente resultado:
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
Chemistry topics are: 'solid physics', Hertz
Maths topics are: 'Fluid Dynamics', Giga Hertz
Chemistry topics are: 'Thermo physics', Decibels
Maths topics are: 'Astro Physics', MegaHertz
Maths topics are: 'Differential Equations', Cosine Series
Integer value is 12
Pi value is 3.14159
Example for Any
Topics 'solid physics', Hertz