arrays - 快速将协议(protocol)数组转换为任何对象

标签 arrays swift casting swift2

我有一个函数 storeInCache 接受一个 AnyObject?

当我尝试给它一个可选的协议(protocol)对象数组时,它失败并出现编译错误“无法使用类型为‘([HasImage]?, String)’的参数调用‘storeInCache’ ”。基本上它不能转换 [有图像]?任何对象?我相信。

我不明白这一点,因为数组包含对象(符合 HasImage 协议(protocol)是),它是一个数组所以它是 AnyObject 否?

我尝试了不同的转换方式,但都没有奏效。 如何快速解决这个问题?

示例代码:

protocol HasImage {
    var imageUrl : String? {get}
}


class Product : NSObject, HasImage {
    var imageUrl : String?
    init(imageUrl : String?) {
        self.imageUrl = imageUrl
    }
}


func storeInCache(obj : AnyObject?, key : String)
{
    //if no object supplied nothing to store in cache!
    //...
}

func testCaching(addDummyData : Bool) {
    var objectsWithImages : [HasImage]?
    if addDummyData {
    objectsWithImages = [Product(imageUrl: "http://wwww.someserver.com/p1/image.jpg"),Product(imageUrl: "http://wwww.someserver.com/p2/image.jpg")]
    }
    //fails compilation with => cannot invoke 'storeInCache' with an argument of list of type '([HasImage]?, String)'
    storeInCache(objectsWithImages,"somekey")
}

最佳答案

将@objc 添加到您的协议(protocol)声明中,它应该没问题,

@objc
protocol HasImage {
    var imageUrl : String? {get}
}

关于arrays - 快速将协议(protocol)数组转换为任何对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32268358/

相关文章:

sql - 使用列名之一的 Postgres FROM 查询

java - 双数组丢失信息

javascript - 是否可以在 for 循环中引用匿名数组?

swift - 如何显示彩色表情符号

c++ - Parent 类型的继承容器不能容纳 child ?

重新排序数组的PHP函数

ios - Swift:手势识别器在将 alpha 更改为 0 并返回 1 后不会注册点击

ios - 当图表设置为在 iOS 图表中滚动时获取当前 x 位置

php - 在 PHP 中将整数转换为字符串

c++ - 将一种类型的数组转换为另一种类型