Swift-유형 주조
인스턴스의 유형을 확인하기 위해 'Type Casting'이 Swift 4 언어로 작동합니다. 인스턴스 유형이 특정 수퍼 클래스 또는 하위 클래스에 속하는지 또는 자체 계층에 정의되어 있는지 확인하는 데 사용됩니다.
Swift 4 유형 캐스팅은 값의 유형과 'as'를 확인하고 유형 값을 다른 유형으로 캐스팅하는 두 개의 연산자 'is'를 제공합니다. 유형 캐스팅은 또한 인스턴스 유형이 특정 프로토콜 준수 표준을 따르는 지 확인합니다.
클래스 계층 정의
유형 캐스팅은 인스턴스 유형을 확인하여 특정 클래스 유형에 속하는지 확인하는 데 사용됩니다. 또한 클래스 및 하위 클래스의 계층 구조를 확인하여 해당 인스턴스를 확인하고 캐스팅하여 동일한 계층 구조로 만듭니다.
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)")
Playground를 사용하여 위의 프로그램을 실행하면 다음과 같은 결과를 얻습니다.
Instance physics is: solid physics
Instance equation is: Hertz
Instance physics is: Fluid Dynamics
Instance formulae is: Giga Hertz
유형 검사
유형 검사는 'is'연산자로 수행됩니다. 'is'유형 검사 연산자는 인스턴스가 특정 하위 클래스 유형에 속하는지 확인하고 해당 인스턴스에 속하면 'true'를 반환하고 그렇지 않으면 '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 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")
Playground를 사용하여 위의 프로그램을 실행하면 다음과 같은 결과를 얻습니다.
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
다운 캐스팅
두 개의 연산자 (as? 및 as!)를 사용하여 하위 클래스 유형을 다운 캐스팅 할 수 있습니다. 값이 nil을 반환하면 선택적 값을 반환합니다. 성공적인 다운 캐스트를 확인하는 데 사용됩니다.
'같이!' 다운 캐스팅이 nil 값을 반환 할 때 선택적 체인에서 논의 된대로 강제 언 래핑을 반환합니다. 다운 캐스트 실패시 런타임 오류를 트리거하는 데 사용됩니다.
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)")
}
}
Playground를 사용하여 위의 프로그램을 실행하면 다음과 같은 결과를 얻습니다.
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
Typecasting : 모든 개체 및 개체
키워드 'Any'는 함수 유형을 포함한 모든 유형에 속하는 인스턴스를 나타내는 데 사용됩니다.
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")
}
}
Playground를 사용하여 위의 프로그램을 실행하면 다음과 같은 결과를 얻습니다.
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
모든 클래스 유형의 인스턴스를 나타 내기 위해 '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")
}
}
Playground를 사용하여 위의 프로그램을 실행하면 다음과 같은 결과를 얻습니다.
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