`==`기호 확장해서 써보기

Zion·2022년 4월 8일
0
struct Ss: Equatable {
    let e: Int
    let f: String
    let g: Double
    
    static func == (lhs:Ss, rhs: Ss) -> Bool {
        return lhs.e == rhs.e && lhs.f == rhs.f || lhs.g == rhs.g
    }
}
class S {
    static func temp() {
        let one = Ss(e: 1, f: "str", g: 1.1)
        let two = Ss(e: 1, f: "str", g: 1.3)
        
        if one == two {
            print("메롱")
        } else {
            print("바보")
        }
    }
}

//print 메롱

변수명이 좀 거지 같다...

하지만 봐보자 !
Swift는 내가 만든 Ss struct가 뭔지 모른다.
그래서

    static func == (lhs:Ss, rhs: Ss) -> Bool {
        return lhs.e == rhs.e && lhs.f == rhs.f || lhs.g == rhs.g
    }

static function으로 확장해준다.
그럼 여기서 .

왜 하필 static 이냐 ~ ?

static : static functions are invoked by a class, rather than an instance of a class. These cannot be overridden by a subclass

라고한다. overriden 하지않게 static으로 만들어주는것으로 이해했다.

profile
어제보다만 나아지는

0개의 댓글