[Swift] Structure

이호정·2022년 2월 9일
0

swift

목록 보기
1/1

//현재 구름EDU에서 코더스하이의 "[애플 공식 교재] iOS 앱 만들기 Part1" 강의를 수강중이다.

구조체

C, C++에서나 접할 수 있던 구조체를 보게 되어 반가웠다.
똑같이 데이터를 묶어서 표현하기 위한 녀석이다.

아래 예시를 보자

struct Person {
  var name: String
  func sayHello() {
    print(”Hello, there! My name is \(name)!”)
  }
}

let person = Person(name: “Jasmine”)
person.sayHello()

Person이라는 구조체는 name이라는 Property를 가지고, sayHello라는 method를 가진다.
Person()으로 인스턴스를 만들고, .(dot)을 이용해 접근한다.

흔히 알고있는 class와 거의 비슷하기에 자잘한 설명은 생략한다.

그럼 여기서 "class와의 차이점은 뭘까?"하는 의문이 자연스레 생기는데,
이와 관련해서는 class를 다룰때 같이 설명할 것이다. (swift에도 class가 있다.)

기억이 안날것 같거나 인상깊었던 부분만 정리해보자.


Initializer

구조체도 class에서의 생성자와 같은 역할을 하는 함수를 가진다.
기본적으로 .init()은 생략해서 사용가능하다. ex) Person.init() = Person()

Default Value

Property들의 Default Value를 설정해놓으면 매개변수 없는 Initializer로 초기화가 가능하다.

struct Person {
  var name: String = "HoJeong"
  func sayHello() {
  	print("Hello, there! My name is \(name)!")
  }
}

let person = Person()
person.sayHello() // Hello, there! My name is HoJeong!

Memberwise Initializer

아무런 init 함수를 정의해놓지 않으면 기본적으로 Memberwise Initializer를 가진다.
init 함수의 매개변수로 property를 설정할 수 있는 Initializer를 뜻한다.

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

//Memberwise Initializer
let me = Person(name: "HoJeong", age: 27)

Custom Initializer

내 마음에 드는 init 함수를 만들 수 있다.
이 경우, 기본적으로 제공되는 Memberwise Initializer는 더이상 제공되지 않는다.

struct Temperature {
  var celsius: Double
 
  init(celsius: Double) {
    self.celsius = celsius
  }
 
  init(fahrenheit: Double) {
    celsius = (fahrenheit - 32) / 1.8
  }
 
  init(kelvin: Double) {
    celsius = kelvin - 273.15
  }
  init() {
    celsius = 0
  }
}
 
let currentTemperature = Temperature(celsius: 18.5) // 18.5
let boiling = Temperature(fahrenheit: 212.0) // 100.0
let absoluteZero = Temperature(kelvin: 0.0) // -273.15
let freezing = Temperature() // 0

Mutating Methods

Instance Method 중에서 property를 변경하는 method가 있을 수 있다.
다른 언어에서는 너무 흔한 일이라 특별히 언급조차 하지 않는데,
swift에서는 이러한 경우를 "mutating" 키워드로 명시해줘야 한다.

struct Counter {
  var count: Int = 0
 
  mutating func increment() {
    count += 1
  }
 
  mutating func increment(by amount: Int) {
    count += amount
  }
 
  mutating func reset() {
    count = 0
  }
}

Computed Properties

swift에서는 계산된 property라는 것이 존재한다.
쉬운 예로 나의 키와 몸무게를 이용해 BMI 지수를 property로 만들고 싶다면?
BMI = 몸무게 / (키 * 키) 를 계산해서 입력해주면 된다.

근데 이걸 키와 몸무게가 바뀔때마다 일일이 계산해서 수정해주기보다, 알아서 계산된다면 얼마나 좋을까?

struct Person {
  var height: Double
  var weight: Double
  var bmi: Double {
  	weight / (height * height)
  }
}

...해결!

Property Observers

swift에서는 property가 변경되기 직전/직후 각각에 실행되는 함수들이 있는데, 이들을 Property Observer라고 부른다.
직전은 willSet, 직후는 didSet 이다. 이들 안에서 바뀔 값은 newValue, 바뀌기전 값은 oldValue로 활용할 수 있다.

struct Counter {
    var count: Int = 0 {
        willSet {
            print(”About to set count to \(newValue)”)
        }
        didSet {
            if count > oldValue  {
                print(”Added \(totalSteps - oldValue) count”)
            }
        }
    }
}

var newCounter = Counter()
newCounter.count = 40
newCounter.count = 100

--------------------------------------------------------------
About to set count to 40
Added 40 count
About to set count to 100
Added 60 count

Type Properties And Methods

이쯤되면, 정적 멤버는 없나? 싶다. 당연하게도 있다!
키워드 static을 이용하면 된다.

struct Student {
  // Type Property
  static var boilingPoint = 100
}

let boilingPoint = Temperature.boilingPoint

Type Method도 똑같이 func 앞에 static을 붙이고, struct 이름으로 접근해서 호출하면 된다.
아래는 Double의 Type method 사용 예시

let biggerNumber = Double.maximum(100.0, -1000.0)

Copying

C++ 였었나, 복사생성자라는 내용이 기억난다.
swift에서 struct instance는 변수(variable)에 대입하거나, 함수의 파라미터로 넘길때
흔히 예상하는 instance의 주소(또는 참조)값을 넘기는게 아니라 안의 값들을 그대로 복사해서 새로 instance를 만들어서 넘긴다.
(새로 instance를 만드는지(즉, Initializer가 호출되는지)는 정확히 모르겠다.)

var someArea = (width: 250, height: 1000)
var anotherArea = someArea
 
someArea.width = 500

print(someArea.width)
print(anotherArea.width)

--------------------------------------------------------------
500
250

오랜만에 구조체를 만나서 반가웠다. 다른 언어들에서의 class를 알고 있는 입장에서,
swift의 class는 어떻게 다를지, struct와 class의 차이점은 무엇일지 궁금해졌다.

0개의 댓글