VesselWheel

[SwiftUI] 구조체 연산자 본문

Xcode Study

[SwiftUI] 구조체 연산자

JasonYang 2023. 4. 26. 13:52

import UIKit

 

// operator methods

 

10 == 10

 

"a" == "a"

 

// 구조체 : 서로 같거나 다른 type 의 변수를 모아놓은 것

// struct 구조체이름 { 변수들... }

 

struct Point{

    var x = 0.0

    var y = 0.0

}

let point1 = Point(x: 12, y: 36)

let point2 = Point(x: 12, y: 36)

 

/*Binary operator '==' cannot be applied to two 'Point' operands

point1 == point2

 */

 

// Point 구조체에서 사용할 == 연산자 작성하기

extension Point: Equatable{

    // (p1: Point, p2: Point) - parameter 로 Point 구조체를 받음

    static func ==(p1: Point, p2: Point) -> Bool{

        return p1.x == p2.x && p1.y == p2.y

    }

}

point1 == point2

 

let point3 = Point(x: 10, y: 20)

let point4 = Point(x: 30, y: 40)

 

point3 == point4

point3 != point4

 

extension Point{

    static prefix func -(pt: Point) -> Point{

        return Point(x: -pt.x, y: -pt.y)

    }

}

 

// let point1 = Point(x: 12, y: 36)

 

let point5 = -point1

point5.x

point5.y

 

extension Point{

    static postfix func ++(pt: inout Point) -> Point{

        pt.x += 1

        pt.y += 1

        return pt

    }

}

var point6 = Point(x: 1.0, y: 2.0)

point6.x

point6.y

 

var point7 = point6++

point6.x

point6.y

 

point7.x

point7.y

type(of: point7.x)

type(of: point7.y)