Could not find an overload for “init” that accepts

2020-02-12 11:37发布

问题:

I am trying to figure out how to translate this in Swift and I am also having this error: "Could not find an overload for “init” that accepts the supplied arguments". Any suggestion appreciated. Thanks.

var pageImages:[UIImage] = [UIImage]()
pageImages = [UIImage(named: "example.png"), UIImage(named: "example2.png")]

回答1:

Confirming what matt says:

in xCode 6.0 this does work:

images = [UIImage(named: "steps_normal"), UIImage(named: "steps_big")]

but in xCode6.1 values should be unwrapped:

images = [UIImage(named: "steps_normal")!, UIImage(named: "steps_big")!]


回答2:

Unwrap those optionals. A UIImage is not the same as a UIImage?, which is what the named: initializer returns. Thus:

var pageImages = [UIImage(named: "example.png")!, UIImage(named: "example2.png")!]

(Unless, of course, you actually want an array of optional UIImages.)



回答3:

UIImage(named:) changed to be a failable initializer in Xcode 6.1, which means that it will return nil if any of the images you've listed are missing from your bundle. To safely load the images, try something like this instead:

var pageImages = [UIImage]()
for name in ["example.png", "example2.png"] {
    if let image = UIImage(named: name) {
        pageImages.append(image)
    }
}