Suyeon9911 / TIL

매일 오전에 적는 미라클 TIL 🥣
11 stars 0 forks source link

[Swift] Method #78

Open Suyeon9911 opened 2 years ago

Suyeon9911 commented 2 years ago

Swift 의 Method 에 관한 총 정리

Suyeon9911 commented 2 years ago

인스턴스 메서드

// 클래스의 인스턴스 메서드
class LevelClass {
    // 현재 레벨을 저장하는 저장 프로퍼티
    var level: Int = 0 {
        // 프로퍼티 값이 변경되면 호출하는 프로퍼티 감시자 
        didSet {
            print(level)
        }
    }

    // 레벨이 올랐을 때 호출하 ㄹ메서드 
    func levelUp() {
        level += 1
    }

    // 레벨이 감소할 때 호출할 메서드
    func levelDown() {
        level -= 1
        if level < 0 {
            reset()
        }
    }

    // 특정 레벨로 이동할 때 호출할 메서드
    func jumpLevel(to: Int) {
        level = to
    }
    // 레벨을 초기화할 때 호출할 메서드 
    func reset() {
        level = 0
    }
}

var levelClassInstance: LevelClass = LevelClass()
levelClassInstance.levelUp()
Suyeon9911 commented 2 years ago

self 프로퍼티

class LevelClass {
    var level: Int = 0

    func reset() {
        // 오류 ! 
        self = LevelClass()
    }
}

struct LevelStruct {
    var level: Int = 0

    mutating func levelUp() {
        level += 1
    }

    mutating func reset() {
        self = LevelStruct()
    }
}

enum OnOffSwitch {
    case on, off
    mutating func nextState() {
        self = self == .on ? .off : .on
    }
}

var toggle: OnOffSwitch = OnOffSwitch.off
toggle.nextState()
print(toggle) // on
Suyeon9911 commented 2 years ago

인스턴스를 함수처럼 호출하도록 하는 메서드

struct Puppy {
    var name: String = "흰둥이"

    func callAsFunction() {
        print("멍멍")
    }

    func callAsFunction(destination: String) {
        print("\(destination)으로 달려갑니다.")
    }
}

var myPuppy: Puppy = Puppy()
myPuppy.callAsFunction()
myPuppy()
myPuppy.callAsFunction(destination: "집")
myPuppy(destination: "집")
Suyeon9911 commented 2 years ago

타입 메서드

class AClass {
    static func staticTypeMethod() {
        print("에이 클래스 타입메서드")
    }

    class func classTypeMethod() {
        print("에이 클래스 클래스 메서드")
    }
}

class BClass: AClass {
    override class func classTypeMethod() {
        print("비 클래스 클래스 메서드")
    }
    // 타입메서드는 재정의 불가능
}

AClass.staticTypeMethod() // 에이 클래스 타입메서드
AClass.classTypeMethod() // 에이 클래스 클래스 메서드
BClass.classTypeMethod() // 비 클래스 클래스 메서드
// 시스템 용량은 함 기기에서 유일한 값
struct SystemVolume {
    // 타입프로퍼티를 사용하면 언제나 유일한 값이 된다.
    static var volume: Int = 5

    // 타입프로퍼티를 제어하기 위해 타입 메서드를 사용
    static func mute() {
        self.volume = 0 // SystemVolume.volume 과 같은 표현, Self.volume과도 같은표현
    }
}

// 내비게이션 역할은 여러 인스턴스가 수행할 수 있다.
class Navigation {
    // 내비게이션 인스턴스마다 음량을 따로 설정할 수 있다.
    var volume: Int = 5

    // 길 안내 음성 재생
    func guideWay() {
        // 내비게이션 외 다른 재생원 음소거
        SystemVolume.mute()
    }

    // 길 안내 음성 종료
    func finishGuideWay() {
        // 기존 재생원 음서 ㅇ복구
        SystemVolume.volume = self.volume
    }
}

SystemVolume.volume = 10
let myNavi: Navigation = Navigation()

myNavi.guideWay()
print(SystemVolume.volume) // 0

myNavi.finishGuideWay()
print(SystemVolume.volume) // 5
Suyeon9911 commented 2 years ago

[Swift] static과 class method, property 효과적으로 사용하기 [Swift] class func vs static func

읽어보면 좋을듯... 수진꽐,, 보곺다..