Swift equivalent for MIN and MAX macros

后端 未结 5 1067
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-02 15:09

In C / Objective-C it is possible to find the minimum and maximum value between two numbers using MIN and MAX macros. Swift doesn\'t support macros and it seems that there a

5条回答
  •  無奈伤痛
    2020-12-02 15:31

    With Swift 5, max(_:_:) and min(_:_:) are part of the Global Numeric Functions. max(_:_:) has the following declaration:

    func max(_ x: T, _ y: T) -> T where T : Comparable
    

    You can use it like this with Ints:

    let maxInt = max(5, 12) // returns 12
    

    Also note that there are other functions called max(_:_:_:_:) and min(_:_:_:_:) that allows you to compare even more parameters. max(_:_:_:_:) has the following declaration:

    func max(_ x: T, _ y: T, _ z: T, _ rest: T...) -> T where T : Comparable
    

    You can use it like this with Floats:

    let maxInt = max(12.0, 18.5, 21, 26, 32.9, 19.1) // returns 32.9
    

    With Swift however, you're not limited to use max(_:_:) and its siblings with numbers. In fact, those functions are generic and can accept any parameter type that conforms to Comparable protocol, may it be String, Character or one of your custom class or struct.

    Thereby, the following Playground sample code works perfectly:

    class Route: Comparable, CustomStringConvertible {
    
        let distance: Int
        var description: String {
            return "Route with distance: \(distance)"
        }
    
        init(distance: Int) {
            self.distance = distance
        }
    
        static func ==(lhs: Route, rhs: Route) -> Bool {
            return lhs.distance == rhs.distance
        }
    
        static func <(lhs: Route, rhs: Route) -> Bool {
            return lhs.distance < rhs.distance
        }
    
    }
    
    let route1 = Route(distance: 4)
    let route2 = Route(distance: 8)
    
    let maxRoute = max(route1, route2)
    print(maxRoute) // prints "Route with distance: 8"
    

    Furthermore, if you want to get the min/max element of elements that are inside an Array, a Set, a Dictionary or any other sequence of Comparable elements, you can use the max() or the min() methods (see this Stack Overflow answer for more details).

提交回复
热议问题