Search code examples
swiftnsarrayxcode6.1

Creating an array of UIImage with NSArray constructor and get error


Here is my code:

override func viewDidLoad() {
        super.viewDidLoad()
        var image1 = UIImage(named: "wide")
        var image2 = UIImage(named: "square")
        var array = NSArray(array: [image1,image2])
        view1 = PhotoCollevtionView(outerFrame: self.view.frame, photoArray: array)
        self.view.addSubview(view1!)
}

This is very simple code but I got a wired error which is:

Cannot invoke 'init' with an argument list of type '(array:$T2)'

at line:

var array = NSArray(array: [image1,image2])

These code were written in Sep 2014 as I remember, at that time, it works pretty well, no error reported. But today I reopened this project and run it, the error showed, and I have no idea why this happened. I found some similar questions, but none of them really helps me with my problem. Does anyone meet the same error before? BTW, my xcode is xcode6.1, thanks guys!


Solution

  • As of Xcode 6.1, UIImage() is a failable initializer. That means, the initialization may fail due to several reasons. If you are absoluteley sure that your images named "wide" and "square" exists you can implicitly unwrap them:

    let image1 = UIImage(named: "wide")
    let image2 = UIImage(named: "square")
    var array = NSArray(array: [image1!,image2!])