iOS Swift错误:'T'无法转换为'MirrorDisposition' [英] iOS Swift Error: 'T' is not convertible to 'MirrorDisposition'

查看:128
本文介绍了iOS Swift错误:'T'无法转换为'MirrorDisposition'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为Array类型创建一个扩展方法,以允许从数组中删除项目

I am attempting to create an extension method for the Array type to allow for removing an item from an array

extension Array {
    func remove(item: AnyObject) {
        for var i = self.count - 1; i >= 0; i-- {
            if self[i] == item {
                self.removeAtIndex(i)
            }
        }
    }
}

在测试条件如果self [i] == item ,我收到以下错误:'T'无法转换为'MirrorDisposition'

On the test condition if self[i] == item, I get the following error: 'T' is not convertible to 'MirrorDisposition'

我试过了许多不同的东西,包括:

I've tried many different things, which include:


  • 使用泛型: remove< T>(item:T)

  • 使用 === 运算符,只提供错误'T'不符合协议'AnyObject'

  • Using generics: remove<T>(item: T)
  • Using the === operator, which just gives the error 'T' does not conform to protocol 'AnyObject'

我是Swift的新手,所以这就是我的知识所在用尽。任何建议都将不胜感激。

I'm new to Swift, so this is where my knowledge runs out. Any suggestions would be greatly appreciated.

推荐答案

您收到错误,因为编译器无法保证存储在您的元素中数组可以与 == 进行比较。您必须确保包含的类型是 Equatable 。但是,没有办法将方法添加到比类本身更具限制性的泛型类中。最好将其作为函数实现:

You are getting an error because the compiler can't guarantee that the element stored in your array can be compared with ==. You have to ensure that it the contained type is Equatable. However, there is no way to add a method to a generic class that is more restrictive than the class itself. It is better to implement it as a function:

func removeItem<T: Equatable>(item: T, var fromArray array: [T]) -> [T] {
    for i in reverse(0 ..< array.count) {
        if array[i] == item {
            array.removeAtIndex(i)
        }
    }
    return array
}

或者你可以添加它是一个更通用的扩展:

Or you could add it as a more generic extension:

extension Array {
    mutating func removeObjectsPassingTest(test: (object: T) -> Bool) {
        for var i : Int = self.count - 1; i >= 0; --i {
            if test(object: self[i]) {
                self.removeAtIndex(i)
            }
        }
    }
}

然后你可以这样做:

var list: [Int] = [1,2,3,2,1]
list.removeObjectsPassingTest({$0 == 2})

这篇关于iOS Swift错误:'T'无法转换为'MirrorDisposition'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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