我有一个函数 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/