상수(let)는 계속해서 변하지않는 하나의 같은 값을 사용하는 것이기 때문에 따로 상수 데이터들을 정리한 파일을 만들어 관리한다. 이렇게 하면 String 등에서 철자 하나로 오류가 나는 것을 방지 할 수 있다.
여기서 핵심은 static 키워드를 사용하여 typeProperty를 만드는 것이다. 이렇게 함으로써 인스턴스를 생성하지 않고 바로 타입에서 타입프로퍼티를 사용할 수 있다.
예제)
Struct Foo {
// typeProperty
static let myName = "tonyWest"
static let myHeight = 189
static let pi = 3.14
static let address = "saemoonangil1"
}
// 인스턴스 생성없이 타입으로 바로 사용 가능
Foo.myName
Foo.myHeight
Foo.pi
Foo.address
static 키워드를 메소드 앞에 붙이는 것 또한 가능하다.
struct Bar {
//typeMethod
static func sayHello() {
print("Hello")
}
}
// 인스턴스 생성없이 사용가능
Bar.sayHello()
클래스에서도 동일한 방식으로 사용한다.
'Swift' 카테고리의 다른 글
Swift - 스위프트 API 디자인 가이드라인 번역 링크! (0) | 2020.03.29 |
---|---|
Swift - Exception Handling(예외처리) (0) | 2020.02.15 |
Swift - for loop (0) | 2020.01.14 |
Swift - Extension (0) | 2020.01.14 |
Swift - Double형 데이터를 String으로 포멧 지정하여 나타내는 법 (0) | 2020.01.10 |