ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Swift 정리 #9 구조체와 클래스
    코딩/Swift 2022. 12. 28. 22:55
    728x90

    구조체와 클래스

    클래스의 인스턴스: 객체

    구조체와 클래스 비교

    구조체와 클래스

    • 값을 저장할 속성 정의
    • 기능을 제공하는 메서드 정의
    • 서브스크립트 구문을 사용하여 해당 값에 대한 액세스를 제공하도록 서브스크립트를 정의
    • 초기화를 정의하여 초기 상태를 설정
    • 기본 구현 이상으로 기능을 확장
    • 특정 종류의 표준 기능을 제공하기 위한 프로토콜 준수


    구조체에 없는 클래스의 추가 기능

    • 상속을 통해 한 클래스가 다른 클래스의 특성을 상속
    • 타입 캐스팅을 사용, 런타임에 클래스 인스턴스의 타입을 확인과 해석
    • 비초기화는 클래스의 인스턴스가 할당한 모든 리소스를 해제
    • 참조 카운팅은 클래스 인스턴스에 대한 하나 이상의 참조를 허용 클래스가 지원하는 추가 기능을 사용하면 복잡성이 증가 일반적으로, 추론하기 쉽기 때문에 구조를 선호 적절하거나 필요할 때 클래스를 사용 실제로 정의하는 대부분의 사용자 정의 데이터 유형이 구조 및 열거형


    클래스와 액터: 많은 동일한 특성과 동작을 공유

    정의 구문

    구조체나 클래스: 타입

    • 타입: UpperCamelCase (예: String, Int 및 Bool)
    • 속성 및 메서드: lowerCamelCase (예: frameRate 및 incrementCount)
    // 구조체 정의: struct
    struct Resolution {
        var width = 0 // 속성, 초기값 0으로 Int 암시적 정의
        var height = 0
    }
    
    // 클래스 정의: class
    class VideoMode {
        var resolution = Resolution() // 구조체 인스턴스
        var interlaced = false
        var frameRate = 0.0
        var name: String? // 옵셔널 타입, 초기값 nil
    }

    구조체와 클래스 인스턴스

    구조체와 클래스 정의는 형태만 정의.
    특정 값을 정하기 위해 인스턴스 생성.

    let someResolution = Resolution() // 새로운 인스턴스 생성
    let someVideoMode = VideoMode()
    // 기본값과 함께 초기화: StructureClassName()

    속성 접근

    // variable.property
    print("The width of someResolution is \(someResolution.width)")
    // Prints "The width of someResolution is 0"
    
    print("The width of someVideoMode is \(someVideoMode.resolution.width)")
    // Prints "The width of someVideoMode is 0"
    
    
    // 새로운 값 지정
    someVideoMode.resolution.width = 1280
    print("The width of someVideoMode is now \(someVideoMode.resolution.width)")
    // Prints "The width of someVideoMode is now 1280"

    구조체의 멤버와이즈 초기화

    // Memberwise Initializer
    // StructureName(propertyName: Value, ... )
    let vga = Resolution(width: 640, height: 480)

    구조체와는 달리, 클래스는 멤버와이즈 초기화가 없다.

    구조체와 Enumeration은 Value Type

    Value type은 변수나 상수에 지정될 때 또는 함수에 전달될 때 값을 복사.
    Value Type

    • Int
    • Float
    • Boolean
    • String
    • Array
    • Dictionary
    • Structure

    NOTE
    컬렉션은 복사될 때 즉시 복사본을 만들지 않고 원본을 공유.
    값이 수정될 때, 수정하기 전 아이템을 복사.

    // 하나의 Structure에서 두 개의 인스턴스 생성
    let hd = Resolution(width: 1920, height: 1080) // Structure의 상수 인스턴스
    var cinema = hd // 새로운 변수 인스턴스
    
    // 두 인스턴스의 값을 각각 바꿔도 서로 영향이 없다.
    cinema.width = 2048
    print("cinema is now \(cinema.width) pixels wide")
    // Prints "cinema is now 2048 pixels wide"
    
    print("hd is still \(hd.width) pixels wide")
    // Prints "hd is still 1920 pixels wide"

    sharedStateStruct_2x

    // Enumeration도 구조체와 동일.
    enum CompassPoint {
        case north, south, east, west
        mutating func turnNorth() {
            self = .north
        }
    }
    var currentDirection = CompassPoint.west
    let rememberedDirection = currentDirection
    currentDirection.turnNorth()
    
    print("The current direction is \(currentDirection)")
    print("The remembered direction is \(rememberedDirection)")
    // Prints "The current direction is north"
    // Prints "The remembered direction is west"

    클래스는 레퍼런스 타입

    레퍼런스 타입: 값을 복사하지 않고 기존 인스턴스를 참조

    let tenEighty = VideoMode() // 클래스의 새로운 상수 인스턴스 생성
    tenEighty.resolution = hd
    tenEighty.interlaced = true
    tenEighty.name = "1080i"
    tenEighty.frameRate = 25.0
    
    let alsoTenEighty = tenEighty // 클래스 상수 인스턴스로부터 새로운 상수 인스턴스 생성
    alsoTenEighty.frameRate = 30.0 // 값 변경
    // 상수의 값 변경 가능한 이유:
    // 상수는 변경되지 않지만, 상수가 참조하는 클래스의 값 변경
    
    print("The frameRate property of tenEighty is now \(tenEighty.frameRate)")
    // Prints "The frameRate property of tenEighty is now 30.0"

    sharedStateClass_2x

    레퍼런스 타입은 유추 곤란.

    Identity Operator(ID 연산자)

    두 개의 상수나 변수가 클래스의 완전히 같은 인스턴스를 참조하는 지 확인하는 연산자.

    • Identical to (===)
    • Not identical to (!==)
    if tenEighty === alsoTenEighty {
        print("tenEighty and alsoTenEighty refer to the same VideoMode instance.")
    }
    // Prints "tenEighty and alsoTenEighty refer to the same VideoMode instance."

    포인터

    레퍼런스 타입의 인스턴스를 참조하는 상수나 변수는 C의 포인터와 유사.
    표준 라이브러리를 통해 포인터나 버퍼 타입 사용 가능.

    728x90

    '코딩 > Swift' 카테고리의 다른 글

    Swift/Tour  (0) 2024.03.02
    Swift 정리 #8 Enumerations  (0) 2022.12.28
    Swift 정리 #7 클로저  (1) 2022.12.14
    Swift 정리 #6 함수  (0) 2022.12.14
    Swift 정리 #5 Control flow  (1) 2022.12.14

    댓글

Designed by Tistory.