gpt4 book ai didi

arrays - 无法在 Array Extension Swift 上从自身调用函数

转载 作者:行者123 更新时间:2023-11-28 11:22:42 25 4
gpt4 key购买 nike

我正在扩展 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是可变的吗?

最佳答案

如果该方法修改了实例本身,则该方法必须是可变的。所以只需在 func 之前添加 mutating 关键字即可。

关于arrays - 无法在 Array Extension Swift 上从自身调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26079642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com