스위프트 문법 : Constants File & Static Keyword (영)

김영채 (Kevin)·2021년 1월 26일
0

iOS & Swift

목록 보기
46/107
post-thumbnail
  • As the size of our app gets bigger and bigger, the number of times we use Strings to specify several tasks also increases

ex.

self.performSegue(withIdentifier: "RegisterToChat", sender: self)
self.performSegue(withIdentifier: "LoginToChat", sender: self)

→ "RegisterToChat" & "LoginToChat" are all programmer-written Strings that are extremely vulnerable to typos. One small typo can lead the app to crash.

→ Hence we need to reduce the number of times we write these Strings in some way.

→ We want to make sure we are accessing these types of Strings using code, instead of typing it every time we need it. Imagine having to Write "PerformSegueToRegisterToChat" every single time you need it somewhere in your code.

Thats why we needs a Constants File

So how do we do it?

  • Create a new Constants.swift file in your project folder

  • Create a struct named "Constants"


→ Notice we made the constants as "static". This is turning it to an instance property to a type property.

ex. Accessing the static constant

Constants.registerSegue

→ We don't have to make an instance of the Constants struct such as below:

let myConstants = Constants()
// Not necessary to access static constants

This is becuase registerSegue and loginSegue are now a type property, instead of an instance property.

profile
맛있는 iOS 프로그래밍

0개의 댓글