xcode 来自“UIImage?”的沮丧?'UIImage' 只解开可选项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26901839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:10:07  来源:igfitidea点击:

Downcast from 'UIImage?' to 'UIImage' only unwraps optionals

iosxcodeswiftuiimage

提问by NetDemo

I'm creating a UIButtonwith an image,

我正在创建一个UIButton图像,

I have written the below code for that:

我为此编写了以下代码:

    let btnImg=UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    let img  = UIImage(named: "turn_left") as UIImage
    btnImg.setTitle("Turn left", forState: UIControlState.Normal)
    btnImg.setImage(img, forState: UIControlState.Normal)
    btnImg.frame = CGRectMake(10, 150, 200, 45)
    self.view.addSubview(btnImg)

But I got the error below at let img = UIImage(named: "turn_left") as UIImage:

但我在以下位置收到错误let img = UIImage(named: "turn_left") as UIImage

Swift Compiler error:
 Downcast from 'UIImage?' to 'UIImage' only unwraps optionals; did you mean to use '!'?

回答by Toseef Khilji

As error Says You have to use '!' ,

正如错误所说您必须使用“!” ,

Try Below code,

试试下面的代码,

   let img  = UIImage(named: "turn_left") as UIImage!  // implicitly unwrapped

OR

或者

   let img : UIImage? = UIImage(named: "turn_left")  //optional

Edit

编辑

After creating imgyou need to check it for nil before using it.

创建后,img您需要在使用之前检查它是否为零。

回答by Dustin Williams

You can always do it in an 'if let' but note the difference in syntax depending on the version of swift.

您始终可以在“if let”中执行此操作,但请注意语法的差异取决于 swift 的版本。

Swift < 2.0:

斯威夫特 < 2.0

if let img = img as? UIImage {

Swift 2.0:

斯威夫特 2.0

if let img = img as UIImage! {

Note the position of the exclamation

注意感叹号的位置

回答by jonogilmour

If the UIImageinitialiser cannot find the file specified (or some other error happened), it will return nil, as per Apple's documentation

如果UIImage初始化程序找不到指定的文件(或发生了其他一些错误),它将返回nil,根据 Apple 的文档

Return Value
The image object for the specified file, or nil if the method could not find the specified image.

So you need to put checks in:

所以你需要检查:

let img  = UIImage(named: "turn_left")
if(img != nil) {
    // Do some stuff with it
}

You don't need to cast a UIImageto a UIImage, that's a waste.

您不需要将 a 转换UIImage为 a UIImage,这是一种浪费。

Edit: Full code

编辑:完整代码

let img  = UIImage(named: "turn_left")
if(img != nil) {
    let btnImg = UIButton.buttonWithType(UIButtonType.Custom) as UIButton
    btnImg.setTitle("Turn left", forState: UIControlState.Normal)
    btnImg.setImage(img, forState: UIControlState.Normal)
    btnImg.frame = CGRectMake(10, 150, 200, 45)
    self.view.addSubview(btnImg)
}

You may want to put an elsein to set the button to a shape or something else that is more likely to work in the case "turn_left" doesn't exist.

您可能想要将else按钮设置为形状或其他在“turn_left”不存在的情况下更有可能起作用的东西。

回答by GrizzlyBear

Since UIImage(named:"something")returns an optional (because it could be nil if the methods doesn't find an appropriate image the best this is not to explicitly unwrap the result (otherwise your app will crash) but to check for the result immediately with something like that:

由于UIImage(named:"something")返回一个可选的(因为如果方法没有找到合适的图像它可能为零,最好不要显式打开结果(否则您的应用程序将崩溃),而是立即使用类似的东西检查结果:

        if let image = UIImage(named: "something"){
        // now you can use image without ? because you are sure to have an image here!
        image.description
        }

    // continue your code here using the optional power of swift's vars! :)

The approach is the following: If the image is optional means that it can be null. Functions that takes in input an optional can handle that, otherwise they usually have unexpected behavior. The UIImage(named:)canreturn nil and you HAVE to handle this. If you explicitly unwrap it you could have problems later.

方法如下:如果图像是可选的,则意味着它可以为空。接受输入可选的函数可以处理这个问题,否则它们通常会出现意外行为。该UIImage(named:)返回nil,你必须处理这个问题。如果你明确地解开它,你以后可能会遇到问题。

With if let something = ...somethingwill be automatically unwrapped in runtime and you can use it safely.

随着if let something = ...东西会在运行时自动解包,您可以放心使用。