Extending Array to check if it is sorted in Swift?

前端 未结 11 2444
清歌不尽
清歌不尽 2020-12-13 14:23

I want to extend Array class so that it can know whether it is sorted (ascending) or not. I want to add a computed property called isSorted. How can I state the

11条回答
  •  天命终不由人
    2020-12-13 15:11

    You've hit a problem with Swift's generics that can't be solved the way you like it right now (maybe in a future Swift version). See also Swift Generics issue.

    Currently, you'll need to define a function (for example at the global scope):

    func isSorted(array: Array) -> Bool {
        for i in 1.. array[i] {
                return false
            }
        }
    
        return true
    }
    
    let i = [1, 2, 3]
    let j = [2, 1, 3]
    let k = [UIView(), UIView()]
    println(isSorted(i)) // Prints "true"
    println(isSorted(j)) // Prints "false"
    println(isSorted(k)) // Error: Missing argument for parameter #2 in call
    

    The error message is misleading, IMHO, as the actual error is something like "UIView doesn't satisfy the type constraint Comparable".

提交回复
热议问题