Franklin
Franklin

Reputation: 891

Swift String overload behavior of '>'

I have a playground:

let astr = "A"
let bstr = "a"

astr > bstr

"A" > "a"

Output: false for the first use of > and an error for the second one:

Playground execution failed: :69:5: error: ambiguous use of operator '>' "A" > "a" ^ Foundation.>:1:6: note: found this candidate func >(lhs: String, rhs: NSString) -> Bool ^ Foundation.>:1:6: note: found this candidate func >(lhs: NSString, rhs: String) -> Bool

This is the drill down of the real problem I am having:

var team = ["Jane","Kate","George","Zulma"]
let sortedteam = team.sorted({ $0 > $1 })

This is giving me the same error.

Upvotes: 1

Views: 104

Answers (1)

Connor
Connor

Reputation: 64644

You can try to use the global sorted function instead, which doesn't have this issue:

var team = ["Jane","Kate","George","Zulma"]
let sortedteam = sorted(team, { $0 > $1 })

Alternatively you could remove some of the conciseness of the closure, so the compiler knows what types it's comparing.

var team = ["Jane","Kate","George","Zulma"]
let sortedteam = team.sorted({ (s1: String, s2: String) in s1 > s2 })

Upvotes: 1

Related Questions