iOS Swift - Property

longlivedrgn·2022년 8월 30일
0

swift문법

목록 보기
13/36
post-thumbnail

먼저 property는 세개가 존재한다.

  • Stored Property(저장 프로퍼티)
  • Computed Property(연산 프로퍼티)
  • Type Property(타입 프로퍼티)

Stored Property

  • 구조체와 클래스에서만 사용이 가능하다.

Stored Properties

  • 기본 꼴
var name : Type = DefaultValue
let name : Type = DefaultValue

만약 init을 주기 싫으면 DefaultValue를 설정해주면 된다.

class Person {
    let name: String = "John Doe" // Variable Stored Property
    var age: Int = 33 // Constant Stored Property
}

Explicit Member Expression

  • Class의 경우
class Person {
    let name: String = "John Doe" // Variable Stored Property
    var age: Int = 33 // Constant Stored Property
}

let p = Person()
p.name //"John Doe"
p.age // 33

// age는 var이므로 변경이 가능하다.
p.age = 30
  • Struct의 경우
    -> let으로 instance를 생성한 경우 Property를 변경할 수 없다.
// 근데 만약 struct로 만든다면?
struct PersonStruct {
    let name: String = "John Doe"
    var age: Int = 33
}

let ps = PersonStruct()

// ps는 상수로 저장하였기에, 모든 속성값은 변경할 수가 없다.
// ps.age = 20 -> 불가능하다.

Lazy Stored Properties

  • lazy는 인스턴스를 생성하는 시점에 값을 부여하고 싶지 않은 변수에 대하여 붙여주는 키워드입니다.
  • lazy의 경우 바로 메모리에 올리지 않는다! ( init함수가 바로 실행되지 않는다.)
  • lazy라는 키워드가 붙으면 초기 값을 주지 않고, 첫 번째 호출 때 초기화를 해주겠다는 의미이기 때문에 변수만 가능해요.
  • 무조건 var로 설정을 해야된다.
    -> 메모리 절약을 위하여 사용을 한다.

참고자료(출처) - https://levenshtein.tistory.com/484#recentComments
https://zeddios.tistory.com/243

Computed Property

  • 클래스, 구조체, 열거형에서 사용이된다.

  • 값을 저장하는게 아니라 연산을 해준다. 즉, 할당하거나 리턴하는 역할만 한다.

  • getter와 setter를 사용하려면 그 연산된 값을 저장할 변수가 반드시 있어야된다.

  • get -> 값 보여주기, set -> 값 재설정하기

  • 예1)

class Point {
    var tempX : Int = 1
    var x: Int { 
    	get { 
        return tempX 
        }
        set(newValue) {
        tempX = newValue * 2} 
        }
     }
var p: Point = Point()
p.x = 12 // tempX에 24라는 값이 저장이된다!
  • 예2)
class Person {
   var name: String
   var yearOfBirth: Int

   init(name: String, year: Int) {
      self.name = name
      self.yearOfBirth = year
   }
    
    var age : Int {
        get {
            let calender = Calendar.current
            let now = Date()
            let year = calender.component(.year, from: now)
            return year - yearOfBirth
        }
        set {
            let calender = Calendar.current
            let now = Date()
            let year = calender.component(.year, from: now)
            yearOfBirth = year - newValue
        }
    }
}

let p = Person(name: "John Doe", year: 2002)
// get 블록 실행
p.age

// set 블록 실행 -> newValue로 들어간다.
p.age = 50 // 50 -> newValue로 들어간다.
p.yearOfBirth // 1972

Read-only Computed Properties

  • get만 있는 연산 프로퍼티이다. 또 get만 있을경우 생략이 가능하다.

아래의 경우, 읽기전용이다!(get도 생략된 상태)

struct Cuboid {
	var width = 0.0, height = 0.0, depth = 0.0
    var volume: Double { 
    return width * height * depth
    }

참고문헌(출처) - https://zeddios.tistory.com/245

Property Observer

  • // willset -> 값이 저장되기 직전에 실행이 된다. parameter가 없으면 newValue

  • // didset -> 값이 저장된 직후에 실행이 된다.parameter가 생략되면 oldValue -> 이전 값을 불러온다!

  • 기본 꼴

var name: Type = DefaultValue{
    willSet(name){
        statements
    }
    didSet(name){
        statements
    }
}
  • 예)
class Size {
    var width = 0.0{
        willSet{
            print(width, "=>", newValue)
        }
        didSet{
            print(oldValue,"=>",width)
        }
    }
}

let s = Size()
s.width = 123

위 코드의 결과는

0.0 => 123.0
0.0 => 123.0

참고/출처 - https://zeddios.tistory.com/247

Type Properties

  • Static을 사용한다.

Stored Type Properties

class Math {
    static let pi = 3.14
}

let m = Math()
// m.pi -> error가 생긴다.
Math.pi // 3.14

Computed Type Properties

enum Weekday: Int {
    case sunday = 1, monday, tuesday, wednesday, thursday, friday, saturday
    
    // get이 생략이된 것이다!
    static var today: Weekday {
        let cal = Calendar.current
        let today = Date()
        let weekday = cal.component(.weekday, from: today)
        return Weekday(rawValue: weekday)!
    }
}

Weekday.today // tuesday

참고/출처 - https://zeddios.tistory.com/251

Self

  • class에서
class Size {
    var width = 0.0
    var height = 0.0

    // self 생략 가능하다.
    func calcArea() -> Double {
        return self.width * self.height
    }
    var area: Double {
        return self.calcArea()
    }

    // self 생략 불가
    func update(width: Double, height: Double){
        self.width = width
        self.height = height
    }

    // closure 안에서는 self 생략 불가
    func doSomething() {
        let c = {self.width * self.height}
    }

    static let unit = ""

    static func doSomething() {
//        self.width  -> 불가능
        self.unit
    }
}

0개의 댓글