Search code examples
swiftmaxdocumentationcombine

example in apple documents for max(by:) operator does not work as described?


I am new to Combine/now learning the operators, I followed the example in the apple developer docs but the output was different in playground https://developer.apple.com/documentation/combine/publisher/max(by:) enter image description here //the website shows

enum Rank: Int {
    case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king
}

let cards: [Rank] = [.five, .queen, .ace, .eight, .jack]
cancellable = cards.publisher
    .max {
        return  $0.rawValue > $1.rawValue
    }
    .sink { print("\($0)") }

// Prints: "queen"

my playground shows:

import Combine

enum Rank: Int {
    case ace = 1, two, three, four, five, six, seven, eight, nine, ten, jack, queen, king
}

let cards: [Rank] = [.five, .queen, .ace, .eight, .jack]
cards.publisher
    .max {
        return  $0.rawValue > $1.rawValue
    }
    .sink { print("\($0)") }
//Prints: "ace"

I tried to solve the "most common name in an array" problem and it only works when I use "<" not ">" to find the max value/

import Combine

var subscriptions = Set<AnyCancellable>()
let nameArray: [String] = ["bob", "james", "bob", "james", "lee", "bob", "bob"]

nameArray
    .filter{ !$0.isEmpty }
    .reduce(into: [String: Int]()){ $0[$1] = ($0[$1] ?? 0) + 1 }
    .publisher
    .max {$0.1 < $1.1 }
    .sink{print($0)}
    .store(in: &subscriptions)

//Prints: "(key: "bob", value: 4)" 

Is it possible the apple document is wrong? or am I doing something wrong?


Solution

  • I think you might be right, that this is a bug in the Apple documentation. The note for the argument to max says it is:

    areInIncreasingOrder

    A closure that receives two elements and returns true if they’re in increasing order.

    You'll notice that increasing order would mean that $0.rawValue would be less than $1.rawValue. The example code uses > instead, but still expects queen to be printed — this doesn't seem right to me. If I flip around the operator to be < instead, it prints queen as expected.

    I encourage you to file a Feedback with Apple about this documentation.