协议扩展中的 .sort 不起作用 [英] .sort in protocol extension is not working

查看:44
本文介绍了协议扩展中的 .sort 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个协议和一个协议扩展,我想在协议扩展中实现一个函数,用自定义对象对协议定义的数组进行排序,但它不起作用.

I have a protocol as well as a protocol extension and I'd like to implement a function in the protocol extension to sort an array defined by the protocol with custom objects, but it's not working.

protocol MyProtocol {
    var myArray: [MyObject] { get set }
}

extension MyProtocol {
    func sortArrayByCreationTime() {
        myArray.sort {
            $0.created > $1.created
        }
    }
}

Xcode 告诉我sort"已重命名为sorted(by:)",但如果我使用它,则会创建一个新数组,但我需要对旧数组进行排序,而不是新数组.

Xcode is telling me that 'sort' has been renamed to 'sorted(by:)', but if im using this a new array gets created, but I need the old array to be sorted, not a new one.

我做错了什么?

推荐答案

这是一个误导性错误 - 问题是您需要将 sortArrayByCreationTime() 方法标记为 mutating 为了告诉编译器它正在改变一个属性(因为协议可以被值和引用类型采用):

It's a misleading error – the problem is that you need to mark your sortArrayByCreationTime() method as mutating in order to tell the compiler that it's mutating a property (as protocols can be adopted by both value and reference types):

extension MyProtocol {
    mutating func sortArrayByCreationTime() {
        myArray.sort {
            $0.created > $1.created
        }
    }
}

这篇关于协议扩展中的 .sort 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆