수색…


통사론

  • let name = json["name"] as? String ?? "" // 출력 : john

  • let name = json["name"] as? String // Output: Optional("john")

  • let name = rank as? Int // Output: Optional(1)

  • let name = rank as? Int ?? 0 // Output: 1

  • let name = dictionary as? [String: Any] ?? [:] // Output: ["name" : "john", "subjects": ["Maths", "Science", "English", "C Language"]]

다운 캐스팅

변수는 형식 캐스트 연산자 as? 사용하여 하위 형식 으로 다운 캐스팅 할 수 as? , 그리고 as! .

as? 연산자 하위 유형으로 캐스팅 하려고 합니다.
실패 할 수 있으므로 선택적입니다.

let value: Any = "John"

let name = value as? String
print(name) // prints Optional("John")

let age = value as? Double
print(age) // prints nil

as! 작업자가 강제 로 캐스트합니다.
선택 사항을 반환하지는 않지만 캐스트가 실패하면 충돌이 발생합니다.

let value: Any = "Paul"

let name = value as! String
print(name) // prints "Paul"

let age = value as! Double // crash: "Could not cast value…"

조건부 언 랩핑을 가진 타입 캐스트 연산자를 사용하는 것이 일반적입니다.

let value: Any = "George"

if let name = value as? String {
    print(name) // prints "George"
}

if let age = value as? Double {
    print(age) // Not executed
}

스위치로 캐스팅

switch 문을 사용하여 다른 유형으로 캐스팅을 시도 할 수도 있습니다.

func checkType(_ value: Any) -> String {
    switch value {

    // The `is` operator can be used to check a type
    case is Double:
        return "value is a Double"

    // The `as` operator will cast. You do not need to use `as?` in a `switch`.
    case let string as String:
        return "value is the string: \(string)"

    default:
        return "value is something else"
    }

}

checkType("Cadena")  // "value is the string: Cadena"
checkType(6.28)      // "value is a Double"
checkType(UILabel()) // "value is something else"

유배

as 연산자는 상위 유형으로 3 스트합니다. 실패 할 수 없으므로 선택 사항을 반환하지 않습니다.

let name = "Ringo"
let value = string as Any  // `value` is of type `Any` now

서브 클래 싱을 포함하는 함수 매개 변수에 다운 캐스트 사용의 예

다운 캐스트는 수퍼 클래스의 매개 변수를 취하는 함수 내부에서 서브 클래스의 코드와 데이터를 사용하는 데 사용될 수 있습니다.

class Rat {
    var color = "white"
}

class PetRat: Rat {
    var name = "Spot"
}

func nameOfRat(🐭: Rat) -> String {
    guard let petRat = (🐭 as? PetRat) else {
        return "No name"
    }
    
    return petRat.name
}

let noName = Rat()
let spot = PetRat()

print(nameOfRat(noName))
print(nameOfRat(spot))

스위프트 언어로 타입 캐스팅


유형 주조

유형 캐스팅은 인스턴스의 유형을 확인하거나 해당 인스턴스를 고유 한 클래스 계층 구조의 다른 수퍼 클래스 또는 서브 클래스로 처리하는 방법입니다.

Swift의 형 변환은 is와 as 연산자로 구현됩니다. 이 두 연산자는 값 유형을 확인하거나 값을 다른 유형으로 변환하는 간단하고 표현적인 방법을 제공합니다.


다운 캐스팅

특정 클래스 유형의 상수 또는 변수는 실제로 장면 뒤에서 하위 클래스의 인스턴스를 참조 할 수 있습니다. 이 경우에는 유형 캐스트 ​​연산자 (예 :? 또는!)를 사용하여 서브 클래스 유형으로 다운 캐스팅을 시도 할 수 있습니다.

다운 캐스팅이 실패 할 수 있기 때문에, 타입 캐스트 연산자는 두 가지 형태로 제공됩니다. 조건부 양식 (?)은 다운 캐스팅하려는 유형의 선택적 값을 반환합니다. 강제 형식 인!은 다운 캐스트를 시도하고 결과를 단일 복합 조치로 강제 취소합니다.

다운 캐스팅이 성공할지 확실하지 않은 경우 유형 캐스트 ​​연산자의 조건부 형식 (?)을 사용하십시오. 이 형식의 연산자는 항상 선택적 값을 반환하며 다운 캐스트가 불가능한 경우이 값은 nil입니다. 이를 통해 성공적인 다운 캐스트를 확인할 수 있습니다.

다운 캐스팅이 항상 성공할 것이라는 확신이들 때만 타입 캐스트 연산자의 강제 형식 (!)을 사용하십시오. 이 형식의 연산자는 잘못된 클래스 유형으로 다운 캐스트하려고하면 런타임 오류를 발생시킵니다. 더 많이 알자.


문자열에서 Int 및 Float 로의 변환 : -

     let numbers = "888.00"
     let intValue = NSString(string: numbers).integerValue
     print(intValue) // Output - 888

     
     let numbers = "888.00"
     let floatValue = NSString(string: numbers).floatValue
     print(floatValue) // Output : 888.0

문자열 변환으로 변환

    let numbers = 888.00
    let floatValue = String(numbers) 
    print(floatValue) // Output : 888.0

    // Get Float value at particular decimal point 
    let numbers = 888.00
    let floatValue = String(format: "%.2f", numbers) // Here %.2f will give 2 numbers after decimal points we can use as per our need
    print(floatValue) // Output : "888.00"

Integer to String 값

    let numbers = 888
    let intValue = String(numbers)
    print(intValue) // Output : "888"

Float to String 값

    let numbers = 888.00
    let floatValue = String(numbers)
    print(floatValue)

선택적 Float 값 (문자열)

    let numbers: Any = 888.00
    let floatValue = String(describing: numbers)
    print(floatValue) // Output : 888.0

선택적 String to Int 값

    let hitCount = "100"
    let data :AnyObject = hitCount
    let score = Int(data as? String ?? "") ?? 0
    print(score)

JSON에서 값 다운 캐스팅

    let json = ["name" : "john", "subjects": ["Maths", "Science", "English", "C Language"]] as [String : Any]
    let name = json["name"] as? String ?? ""
    print(name) // Output : john
    let subjects = json["subjects"] as? [String] ?? []
    print(subjects) // Output : ["Maths", "Science", "English", "C Language"]

선택적 JSON의 값 다운 캐스팅

    let response: Any = ["name" : "john", "subjects": ["Maths", "Science", "English", "C Language"]]
    let json = response as? [String: Any] ?? [:]
    let name = json["name"] as? String ?? ""
    print(name) // Output : john
    let subjects = json["subjects"] as? [String] ?? []
    print(subjects) // Output : ["Maths", "Science", "English", "C Language"]

조건이있는 JSON 응답 관리

    let response: Any = ["name" : "john", "subjects": ["Maths", "Science", "English", "C Language"]] //Optional Response 
    
    guard let json = response as? [String: Any] else {
        // Handle here nil value
        print("Empty Dictionary")
        // Do something here
        return
    }
    let name = json["name"] as? String ?? ""
    print(name) // Output : john
    let subjects = json["subjects"] as? [String] ?? []
    print(subjects) // Output : ["Maths", "Science", "English", "C Language"]

조건에 따라 무응답 관리

    let response: Any? = nil
    guard let json = response as? [String: Any] else {
        // Handle here nil value
        print("Empty Dictionary")
        // Do something here
        return
    }
    let name = json["name"] as? String ?? ""
    print(name) 
    let subjects = json["subjects"] as? [String] ?? []
    print(subjects) 

출력 : Empty Dictionary




Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow