3.5 Constant and Variable Scope

Joohyun·2022년 4월 15일
0

Scope

Global Scope

  • 프로그램 어디에서나 이용 가능한 코드
// global variable
var age = 55
 
func printMyAge() {
  print(My age: \(age))
}
 
print(age)
printMyAge()

Local Scope

  • structure, class, if, for loop 등등 { } 내부

  • local scope에 선언된 constant 또는 variable은 바깥 구역에서 이용할 수 없다.

func printBottleCount() {

  // local constant
  let bottleCount = 99
  print(bottleCount)
}
 
printBottleCount()
print(bottleCount) // Error

Variable Shadowing

  • 더 좁은 scope에 같은 이름을 가진 값을 선언하여 바깥 scope에 위치한 값을 가린다.

  • 적절히 사용하면 더 깔끔한 코드를 유지할 수 있다.

func printComplexScope() {

	// function's local scope
    let points = 100
    print(points)
 
    for index in 1...3 {
    
    	// for loop's local scope
        // function's local scope를 완전히 가림(shadowing)
        // 이 곳에서는 100에 접근할 수 없다.
        let points = 200
        print(Loop \(index): \(points+index))
    }
 
    print(points)
}
 
printComplexScope()
// console
100
Loop 1: 201
Loop 2: 202
Loop 3: 203
100

variable shadowing을 쓰는 케이스

1. if let

  • if let에서 같은 이름의 constant에 optional에서 추출한 값을 할당하여 내부에서 사용
func exclaim(name: String?) {
  if let name = name {
  
    // if let 내부에서의 `name`은 `String?`에서 값을 추출한 `String` 값이다.
    print(Exclaim function was passed: \(name))
  }
}

2. guard

  • guard에서 같은 이름의 constant에 optional에서 추출한 값을 할당

  • guard 아랫부분의 코드는 더이상 optional값에 접근할 수 없다.

func exclaim(name: String?) {
  guard let name = name else { return }
  
  // `String?`값의 name은 더이상 접근할 수 없다.
  // `String`값의 name만 접근 가능
  print(Exclaim function was passed: \(name))
}

3. Initializer

  • initializer의 parameter 이름을 해당 type의 property와 같게 설정

  • initializer 내부

    • 해당 이름을 통해 parameter 값에 접근

    • self 키워드를 통해 property에 접근 가능

struct Person {
  var name: String
  var age: Int

  init(name: String, age: Int) {
  	// property에 parameter 값을 할당
    self.name = name
    self.age = age
  }
}
profile
IOS Developer

0개의 댓글