无法在Array Extension Swift上调用self函数

时间:2014-09-27 22:06:25

标签: arrays sorting swift

我正在快速扩展Array课程。我需要对数组进行排序,但是当我尝试它时会给出错误Immutable value of type 'Array<T>' only has mutating members named 'sort'

这是我的扩展名:

import UIKit

extension Array {

    func sortedArrayByTimeUsingKey(key: String, ascending: Bool) {

        sort { (firstObject, secondObject) -> Bool in

            let firstDict = firstObject as [String: AnyObject]
            let secondDict = secondObject as [String: AnyObject]

            let firstDateString = firstDict[key]! as String
            let secondDateString = secondDict[key]! as String

            let dateFormatter = DateFormatter()

            let firstDate = dateFormatter.dateFromString(firstDateString)!
            let secondDate = dateFormatter.dateFromString(secondDateString)!

            let order = firstDate.compare(secondDate)

            switch order {
            case .OrderedAscending:
                return ascending ? true : false
            case .OrderedDescending:
                return ascending ? true : false
            default:
                return true
            }
        }
    }

}

如何将self变为可变或如何检查self是否可变?

2 个答案:

答案 0 :(得分:2)

如果方法修改了实例本身,则该方法需要是一个变异的方法。所以只需在func。

之前添加mutating关键字

答案 1 :(得分:1)

刚刚找到了答案:在mutating

之前添加func