swift 4(구조체와 클래스, 프로퍼티와 메서드)

1 분 소요

2020.03.18

‘야곰. 스위프트 프로그래밍 3판. 한빛미디어’를 바탕으로 작성되었습니다.

9장 구조체와 클래스

  • 구조체 : 값 타입
  • 클래스 : 참조 타입
  • 중첩 구조체, 클래스 정의가 가능합니다.

구조체

struct Person {
    var name: String;
    var age: Int;
}

let person1: Person = Person(name: "Alice", age: 12);
print(person1.name);
print(person1.age);

person1.name = "Bob";       // 변경 불가

클래스

class Person {
    var name: String = "";
    var age: Int = 0;

    deinit {
        print("Deinitializer Person class");
    }
}

let person1: Person = Person();     // 참조 타입이므로 상수로 선언해도 내부 프로퍼티 값을 변경 가능

person1.name = "Alice";
person1.age = 12;

var person2: Person? = Person();
person2 = nil;                      // deinit 호출

10장 프로퍼티와 메서드

프로퍼티

  • 연산 프로퍼티 : 특정 상태에 따른 값을 연산하는 프로퍼티
  • 연산 프로퍼티를 사용하면 getter, setter 보다 더욱 가독성 좋은 코드가 될 수 있습니다.
  • 타입 프로퍼티는 모든 인스턴스가 공통으로 사용한 값입니다.
  • 타입 프로퍼티는 multi-thread에 safe 합니다.
struct CoordinatePoint {
    var x: Int;             // 저장 프로퍼티
    var y: Int;             // 저장 프로퍼티

    var oppositePoint: CoordinatePoint {            // 연산 프로퍼티
        get {
            return CoordinatePoint(x: -x, y: -y);
        }
        set(opposite) {
            x = -opposite.x;
            y = -opposite.y;
        }
    }
}

class Position {
    static var typeProperty: Int = 0;   // 타입 프로퍼티

    var point: CoordinatePoint?;    // 옵셔널 설정을 해주면 인스턴스 생성 시 값이 없어도 됩니다.
    var name: String {
        willSet {                   // 프로퍼티 감시자
            print("\(name) -> \(newValue)");
        }

        didSet {
            print("\(oldValue) -> \(name)");
        }
    }

    init(name: String) {
        self.name = name;
    }
}


var myPosition: Position = Position(name: "Philip");
print(myPosition.point);        // nil
print(myPosition.name);         // Philip

myPosition.name = "Bosung";
// Philip -> Bosung
// Philip -> Bosung
  • 키 경로
class Person {
    var name: String;
    init(name: String) {
        self.name = name;
    }
}

var person1 = Person(name: "Philip");
let personNamePath = \Person.name;

print(person1[keyPath: personNamePath]);        // Philip

메서드

  • 메서드 앞에 mutating 키워드를 붙여서 인스턴스 내부 값을 수정한다는 것을 명시합니다.
struct SomeStruct {
    var num: Int = 0;

    mutating func plus() {
        num += 1;
    }

    mutating func minus() {
        num -= 1;
    }
}
  • 구조체나 열거형 등은 self 프로퍼티로 자기 자신을 치환할 수 있습니다.
struct SomeStruct {
    var num: Int = 10;

    init(num: Int) {
        self.num = num;
    }

    mutating func reset() {
        self = SomeStruct(num: 0);
    }
}

카테고리:

업데이트:

댓글남기기