Swift

[Swift] self vs Self

Sky Titan 2021. 12. 8. 20:52
728x90

self

  • 해당 타입의 인스턴스에 대한 참조를 나타낸다.
  • instance property, instance method 등을 참조한다.

 

Self

  • 해당 타입 자체에 대한 참조를 나타낸다.
  • type property, type method 등을 참조한다.

 

import UIKit

class Test {
    
    static var className: String = "Test"
    
    var instanceName: String = ""

    func printClassName() {
        print(Self.className)
    }
    
    func printInstanceName() {
        print(self.instanceName)
    }
}

let test = Test()
test.instanceName = "Test instance 1"

let test2 = Test()
test2.instanceName = "Test instance 2"

test.printInstanceName()
test.printClassName()
test2.printInstanceName()
test2.printClassName()
/*
Test instance 1
Test
Test instance 2
Test
*/
728x90