iOS/🟠 Swift

[Swift] μ—°μ‚°μž κ΅¬ν˜„ (Implementing Operator Methods)

woozzang 2021. 3. 18. 20:40

μš°λ¦¬κ°€ μ•„λŠ” μ—°μ‚°μžλ“€μ€ λͺ¨λ“  νƒ€μž…μ„ μ§€μ›ν•˜μ§€λŠ” μ•ŠμŠ΅λ‹ˆλ‹€.

+, -, ,%, /, // λ“±

 

예λ₯Ό λ“€λ©΄ μ»€μŠ€ν…€ νƒ€μž…μ— λŒ€ν•΄, μš°λ¦¬λŠ” 직접 μ—°μ‚°μžλ₯Ό κ΅¬ν˜„ν•΄μ•Ό ν•©λ‹ˆλ‹€.

 


 

κΈ°λ³Έ νŒ¨ν„΄

static func operator (paramters) -> ReturnType {
	...
}

operator μ—λŠ” μ—°μ‚°μžκ°€ λ“€μ–΄κ°‘λ‹ˆλ‹€.

 

parameters μ—λŠ” μ—°μ‚°μžμ˜ μ•ž κ³Ό 뒀에 뢙을 ν•­(μ’Œν•­, μš°ν•­ ν˜Ήμ€ 단항)λ“€μ˜ 값을 νŒŒλΌλ―Έν„°λ‘œ λ°›κ²Œ λ©λ‹ˆλ‹€.

 

ReturnType 은 μ—°μ‚°κ²°κ³Ό κ°’μ˜ νƒ€μž…μž…λ‹ˆλ‹€. 예λ₯Ό λ“€μ–΄ '==' (equal to) μ—°μ‚°μžλΌλ©΄ Bool을 λ°˜ν™˜ν•  κ²ƒμž…λ‹ˆλ‹€.


 

ν™œμš©

struct Point {

    var x: Double
    var y: Double 
    
    static func ==(lhs: Point, rhs: Point) -> Bool {
        return (lhs.x == rhs.x) && (lhs.y == rhs.y)
    }
    
    static func *(lhs: Point, rhs: Point) -> Point {
        return Point(x: lhs.x * rhs.x, y: lhs.y * rhs.y)
    }
    
    static prefix func -(value: Point) -> Point {
        return Point(x: -value.x, y: -value.y)
    }
    
    static postfix func ++(value: inout Point) -> Point {
        let originValue = value
        value.x += 1.0
        value.y += 1.0
        return originValue
    }
}

 

Point λΌλŠ” μ»€μŠ€ν…€ νƒ€μž… (struct) 에 μ‚¬μš©ν•  수 μžˆλŠ” μ—°μ‚°μž ( == , * , λ‹¨ν•­μ—°μ‚°μž -, ν›„ν–‰μ—°μ‚°μž ++ ) λ₯Ό κ΅¬ν˜„ν•΄ λ³΄μ•˜μŠ΅λ‹ˆλ‹€.

 

μ½”λ“œλ₯Ό 보면 κ°„λ‹¨ν•˜κ²Œ 이해할 수 μžˆμœΌλ―€λ‘œ μ„€λͺ…은 μƒλž΅ν•˜κ² μŠ΅λ‹ˆλ‹€ !! πŸ‘πŸ»


 

" μ—°μ‚°μžλ„ ν•¨μˆ˜μž…λ‹ˆλ‹€ "

ν•¨μˆ˜λŠ” 일급 객체 μ΄λ―€λ‘œ λ³€μˆ˜μ— μ €μž₯, νŒŒλΌλ―Έν„°λ‘œ 전달, 리턴 κ°’μœΌλ‘œ μ‚¬μš©μ΄ κ°€λŠ₯ν•©λ‹ˆλ‹€.

 

λŒ€ν‘œμ μΈ κ³ μ°¨ν•¨μˆ˜μΈ map, filter, reduce λ“±μ˜ λ‘λ²ˆμ§Έ νŒŒλΌλ―Έν„°μ—  '+', '-' 와 같은 μ—°μ‚°μžλ§Œ 전달할 수 μžˆλŠ” μ΄μœ λŠ” μ—°μ‚°μžλ„ ν•¨μˆ˜μ΄κΈ° λ•Œλ¬Έμž…λ‹ˆλ‹€.

 

μ˜€λŠ˜λ„ 초보적인 μ§ˆλ¬Έμ„ ν•˜λŠ” λ‚˜

 

 

 

끝!