본문 바로가기

Swift

Swift - Constants(상수) 다루기 with Static 키워드(typeProperty, type Method)

상수(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()

 

클래스에서도 동일한 방식으로 사용한다.