Swift:UIImage - 找不到“初始化”的过载。接受提供的参数

时间:2015-01-16 18:18:08

标签: swift ios8 uiimage

下面是我用来构建图像数组的代码

var _displayImage : Array<UIImage>!

required init(coder aDecoder: NSCoder) {
    self._displayImage = []
}

func buildImageSet() {
    self._displayImage = [UIImage(named: "image1"), UIImage(named: "image2"), UIImage(named: "image3"), UIImage(named: "image4"), UIImage(named: "image5")]
}

我收到错误:找不到接受提供的参数的'init'的重载

enter image description here

我做错了什么?

1 个答案:

答案 0 :(得分:5)

问题是你声明了你的数组:

var _displayImage : Array<UIImage>!

所以期待UIImage个对象。问题是UIImage(named:String)会返回UIImage?个可选项。快速解决方法是切换它:

func buildImageSet() {
    self._displayImage = [UIImage(named: "image1"), UIImage(named: "image2"), UIImage(named: "image3"), UIImage(named: "image4"), UIImage(named: "image5")]
}

对此:

func buildImageSet() {
    self._displayImage = [UIImage(named: "image1")!, UIImage(named: "image2")!, UIImage(named: "image3")!, UIImage(named: "image4")!, UIImage(named: "image5")!]
}

虽然这没有考虑到任何这些图像可能是nil的可能性。如果任何图像无法正确加载,您的应用程序将崩溃。如果你确定它们都存在并且将永远存在,这应该没问题。 :)