English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Swift 타입 변환

Swift 언어의 타입 변환은 예제의 타입을 판단할 수 있으며, 예제 타입이 부모 클래스나 서브 클래스의 예제인지 확인할 수도 있습니다.

Swift에서 타입 변환은 is와 as 연산자를 사용하여 구현됩니다. is는 값을 타입을 확인하는 데 사용되고, as는 타입을 변환하는 데 사용됩니다.

타입 변환은 클래스가 특정 프로토콜을 구현했는지 확인하는 데도 사용될 수 있습니다.

클래스 계층 구조 정의

아래는 세 개의 클래스를 정의한 것입니다: Subjects, Chemistry, Maths, Chemistry와 Maths는 Subjects를 상속합니다.

아래는 코드입니다:

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 = [
    화학(물리학: "고체물리학", 공식: "헤르츠"),
    Maths(physics: "流体力学", formulae: "千兆赫")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("示例物理学是: \(samplechem.physics)")
print("示例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("示例物理学是: \(samplemaths.physics)")
print("示例公式是: \(samplemaths.formulae)")

이 프로그램 실행 결과는 다음과 같습니다:

예제 물리학은: 고체 물리학
예제 방정식은: 헤르츠
예제 물리학은: 유체 역학
예제 공식은: گی가헤르츠

타입 확인

타입 변환은 예제의 타입이 특정 예제 타입에 속하는지 확인하는 데 사용됩니다.

그를 클래스와 서브 클래스의 계층 구조에 사용할 수 있습니다. 특정 클래스 예제의 타입을 확인하고, 이 계층 구조에서 다른 타입으로 변환할 수 있습니다.

타입 확인은 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 = [
    화학(물리학: "고체물리학", 공식: "헤르츠"),
    수학(물리학: "유체역학", 공식: "기가헤르츠"),
    화학(물리학: "열물리학", 공식: "데시벨"),
    Maths(physics: "天体物理学", formulae: "兆赫"),
    Maths(physics: "微分方程", formulae: "余弦级数")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("示例物理学是: \(samplechem.physics)")
print("示例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("示例物理学是: \(samplemaths.physics)")
print("示例公式是: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
    // Chemistry 타입의 예제인 경우 true를 반환하고, 그렇지 않으면 false를 반환합니다.
    if item is Chemistry {
        ++chemCount
    else if item is Maths {
        ++mathsCount
    }
}
화학 과목은 \(chemCount) 개의 주제를 포함하고, 수학은 \(mathsCount) 개의 주제를 포함합니다.

이 프로그램 실행 결과는 다음과 같습니다:

예제 물리학은: 고체 물리학
예제 방정식은: 헤르츠
예제 물리학은: 유체 역학
예제 공식은: گی가헤르츠
화학 과목을 포함합니다. 2 테마를 포함합니다. 3 테마

다운캐스팅

다운캐스팅은 타입 변환 연산자(as? 또는 as!)로 합니다

다운캐스팅이 성공할 수 없을 때는 조건 형식의 타입 변환(as?)을 사용하세요. 조건 형식의 타입 변환은 항상 선택 가능한 값을 반환하며, 다운캐스팅이 불가능할 때 선택 가능한 값은 nil입니다。

다운캐스팅이 항상 성공할 수 있다고 확신할 때만 강제 형식(as!)을 사용하세요. 잘못된 타입으로 다운캐스팅을 시도하면 강제 형식의 타입 변환은 실행 시간 오류를 일으킵니다。

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 = [
    화학(물리학: "고체물리학", 공식: "헤르츠"),
    수학(물리학: "유체역학", 공식: "기가헤르츠"),
    화학(물리학: "열물리학", 공식: "데시벨"),
    Maths(physics: "天体物理学", formulae: "兆赫"),
    Maths(physics: "微分方程", formulae: "余弦级数")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("示例物理学是: \(samplechem.physics)")
print("示例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("示例物理学是: \(samplemaths.physics)")
print("示例公式是: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
    // 类型转换的条件形式
    if let show = item as? Chemistry {
        print("化学主题是: '\(show.physics)', \(show.equations)")
        // 强制形式
    } else if let example = item as? Maths {
        print("数学主题是: '\(example.physics)',  \(example.formulae)")
    }
}

이 프로그램 실행 결과는 다음과 같습니다:

예제 물리학은: 고체 물리학
예제 방정식은: 헤르츠
예제 물리학은: 유체 역학
예제 공식은: گی가헤르츠
화학 주제는: '고체 물리학', 헤르츠
수학 주제는: '유체 역학', گی가헤르츠
화학 주제는: '열물리학', 데시벨
수학 주제는: '천체 물리학', 메가헤르츠
수학 주제는: '미분 방정식', 余弦 정수열

Any와 AnyObject의 타입 변환

Swift는 불확실한 타입에 대해 두 가지 특별한 타입 별명을 제공합니다:

  • AnyObject任何class类型的示例都可以代表。
  • Any任何类型都可以表示,包括方法类型(function types)。

주의:
behaviour과 function을 명확히 필요로 할 때만 사용하세요Any그리고AnyObject코드에서 원하는 명확한 타입을 사용하는 것이 항상 더 좋습니다.

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 = [
    화학(물리학: "고체물리학", 공식: "헤르츠"),
    수학(물리학: "유체역학", 공식: "기가헤르츠"),
    화학(물리학: "열물리학", 공식: "데시벨"),
    Maths(physics: "天体物理学", formulae: "兆赫"),
    Maths(physics: "微分方程", formulae: "余弦级数")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("示例物理学是: \(samplechem.physics)")
print("示例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("示例物理学是: \(samplemaths.physics)")
print("示例公式是: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in sa {
    // 类型转换的条件形式
    if let show = item as? Chemistry {
        print("化学主题是: '\(show.physics)', \(show.equations)")
        // 强制形式
    } else if let example = item as? Maths {
        print("数学主题是: '\(example.physics)',  \(example.formulae)")
    }
}
// Any 타입의 배열 exampleany를 저장할 수 있습니다.
var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Any 示例")
exampleany.append(Chemistry(physics: "固体物理", equations: "兆赫"))
for item2 in exampleany {
    switch item2 {
    case let someInt as Int:
        출력("정수 값은 \(someInt)")
    case let someDouble as Double where someDouble > 0:
        출력("파이 값은 \(someDouble)")
    case let someString as String:
        print("\(someString)")
    case let phy as Chemistry:
        print("주제 '\(phy.physics)', \(phy.equations)")
    default:
        print("None")
    }
}

이 프로그램 실행 결과는 다음과 같습니다:

예제 물리학은: 고체 물리학
예제 방정식은: 헤르츠
예제 물리학은: 유체 역학
예제 공식은: گی가헤르츠
화학 주제는: '고체 물리학', 헤르츠
수학 주제는: '유체 역학', گی가헤르츠
화학 주제는: '열물리학', 데시벨
수학 주제는: '천체 물리학', 메가헤르츠
수학 주제는: '미분 방정식', 余弦 정수열
정수 값은 12
파이 값은 3.14159
Any 예제
주제 '고체 물리학', 메가헤르츠

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)
    }
}
// AnyObject 타입의 배열
let saprint: [AnyObject] = [
    화학(물리학: "고체물리학", 공식: "헤르츠"),
    수학(물리학: "유체역학", 공식: "기가헤르츠"),
    화학(물리학: "열물리학", 공식: "데시벨"),
    Maths(physics: "天体物理学", formulae: "兆赫"),
    Maths(physics: "微分方程", formulae: "余弦级数")]
let samplechem = Chemistry(physics: "固体物理", equations: "赫兹")
print("示例物理学是: \(samplechem.physics)")
print("示例方程式: \(samplechem.equations)")
let samplemaths = Maths(physics: "流体动力学", formulae: "千兆赫")
print("示例物理学是: \(samplemaths.physics)")
print("示例公式是: \(samplemaths.formulae)")
var chemCount = 0
var mathsCount = 0
for item in saprint {
    // 类型转换的条件形式
    if let show = item as? Chemistry {
        print("化学主题是: '\(show.physics)', \(show.equations)")
        // 强制形式
    } else if let example = item as? Maths {
        print("数学主题是: '\(example.physics)',  \(example.formulae)")
    }
}
var exampleany = [Any]()
exampleany.append(12)
exampleany.append(3.14159)
exampleany.append("Any 示例")
exampleany.append(Chemistry(physics: "固体物理", equations: "兆赫"))
for item2 in exampleany {
    switch item2 {
    case let someInt as Int:
        출력("정수 값은 \(someInt)")
    case let someDouble as Double where someDouble > 0:
        출력("파이 값은 \(someDouble)")
    case let someString as String:
        print("\(someString)")
    case let phy as Chemistry:
        print("주제 '\(phy.physics)', \(phy.equations)")
    default:
        print("None")
    }
}

이 프로그램 실행 결과는 다음과 같습니다:

예제 물리학은: 고체 물리학
예제 방정식은: 헤르츠
예제 물리학은: 유체 역학
예제 공식은: گی가헤르츠
화학 주제는: '고체 물리학', 헤르츠
수학 주제는: '유체 역학', گی가헤르츠
화학 주제는: '열물리학', 데시벨
수학 주제는: '천체 물리학', 메가헤르츠
수학 주제는: '미분 방정식', 余弦 정수열
정수 값은 12
파이 값은 3.14159
Any 예제
주제 '고체 물리학', 메가헤르츠

switch 문의 case에서 강제 형식의 타입 변환 연산자 (as, 대신 as?)를 사용하여 명확한 타입으로 검사 및 변환합니다.