part2. 프로퍼티와 메서드2

구름코딩·2020년 9월 9일

메서드

메서드는 특정 타입에 관련된 함수

클래스, 구조체, 열거형 등은 실행하는 기능을 캡슐화한 인스턴스 메서드를 정의할 수 있다
또한, 타입자체와 관련된 기능을 실행하는 타입 메서드를 정의할 수 있다

프로그래머가 정의하는 타입(클래스, 구조체, 열거형 등)에 자유롭게 메서드를 정의할수 있다

인스턴스 메서드

특정 타입의 인스턴스에 속한 함수

  • 인스턴스 내부의 프로퍼티값을 변경하거나 특정 연산 결과를 반환하는 등 인스턴스와 관련된 기능을 실행
  • 특정 타입 내부에 구현한다, 따라서 인스턴스가 존재할때만 사용할수 있다
	class LevelCalss {
        var level: Int  = 0{
            didSet {
                print("Level \(level)")
            }
        }

        //레벨업
        func levelUp() {
            self.level += 1
            print("Level Up!")
        }

        //레벨다운
        func levelDown() {
            level -= 1
            print("Level Down...")
            if level < 0 {
                levelReset()
            }
        }

        //레벨 점프
        func levelJump(to: Int) {
            if to > 0 {
                level = to
                print("level Jump!")
            }
            else {
                print("해당 레벨로 이동할수없습니다")
            }
        }

        //레벨 리셋
        func levelReset() {
            level = 0
            print("reset Level!")
        }
	}
    
    let gameCharacter: LevelCalss = LevelCalss()
    gameCharacter.levelReset()
    gameCharacter.levelUp()
    gameCharacter.levelDown()
    gameCharacter.levelJump(to: 10)
    gameCharacter.levelJump(to: -10)
    gameCharacter.levelReset()

여기서 class의 인스턴스 메서드는 자신의 프로퍼티 값을 변경할 때가 아닌 구조체나 열거형 등은 값타입이므로 메서드 앞에 mutating키워드를 붙여서 해당 메서드가 인스턴스 내부의 값을 변경한다는 것을 명시해야한다

struct levelStruct {
	var level: Int = 0 {
    	didSet {
        	print("Level \(level)")
		}
}

mutating func levelUp() {
	print("level Up!")
    level += 1
}

self프로퍼티

모든 인스턴스는 암시적으로 생성된 self프로퍼티를 갖는다

참조타입인 클래스의 인스턴스와 다르게 구조체나 열거형등은 self프로퍼티에 다른 참조를 할당하여 자기 자신을 치환할수 있다

class Level {
        var level: Int = 0
        
//        func reset() {
//            self = Level()
//        }
    }
    
    struct LevelStruct {
        var level: Int = 0
        
        mutating func levelUp() {
            print("level Up")
            level += 1
        }
        
        mutating func reset() {
            print("Reset")
            self = LevelStruct()
        }
    }
    
    var levelStructInstance: LevelStruct = LevelStruct()
    levelStructInstance.levelUp()
    print(levelStructInstance.level)
    
    levelStructInstance.reset()
    print(levelStructInstance.level)
    
    enum OnOffSwitch {
        case on, off
        mutating func nextState() {
            self = self == .on ? .off : .on
        }
    }
    var toggle: OnOffSwitch = OnOffSwitch.on
    toggle.nextState()
    print(toggle)
//
level Up
1
Reset
0
off

타입 메서드

메서드에서도 인스턴스 메서드와 타입메서드 존재

타입 자체에 호출이 가능한 메서드를 타입 메서드라 부른다, 타입 인스턴스와 마찬가지로 static 키워드를 사용
단, static으로 정의하면 상속 후 메서드 재정의가 불가능하며 class로 정의하면 상속 후 메서드 재정의가 가능

 class AClass {
        static func staticTypeMethod() {
            print("AClass staticTypeMethod")
        }
        class func classTypeMethod() {
            print("AClass classTypeMethod")
        }
    }
    class BClass: AClass {
//        override static func staticTypeMethod() {
//            //static은 재정의 불가능
//        }
        override class func classTypeMethod() {
            print("BClass classTypeMethod")
        }
    }
    AClass.staticTypeMethod()
    AClass.classTypeMethod()
    BClass.classTypeMethod()
//
AClass staticTypeMethod
AClass classTypeMethod
BClass classTypeMethod

타입프로퍼티와 타입메서드의 사용

	struct SystemVolume {
        static var volume: Int = 5
        
        static func mute() {
            self.volume = 0
        }
    }
    class Navigator {
        var volume: Int = 5
        
        func guideWay() {
           SystemVolume.mute()
        }
        func finishGuideWay() {
            SystemVolume.volume = self.volume
            //여기서 self는 Navigator이다
        }
    }
    
    SystemVolume.volume = 10
    print(SystemVolume.volume)
    let myNavi: Navigator = Navigator()
    myNavi.guideWay()
    print(SystemVolume.volume)
    
    myNavi.volume = 7
    myNavi.finishGuideWay()
    print(SystemVolume.volume)
//
10
0
7
profile
내꿈은 숲속의잠자는공주

0개의 댓글