为什么在枚举和切换的情况下需要打包? [英] Why force unwrapping is required in case of enum and switch?

查看:139
本文介绍了为什么在枚举和切换的情况下需要打包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到奇怪的swift行为,因为在我看来,颜色变量不应该被强制解开,以防止在下面的开关的情况下,但没有解开编译器显示一个错误消息。

 枚举颜色:Int {
case Red = 0,White,Black
}

var colors:Colors!
colors = .Red

开关颜色! {//< - 为什么我必须打开颜色?你可以看到颜色被声明为'!'
case .Red:break
默认值:break
}

如果颜色变量未解开编译器显示我的错误:



在我看来,它是快速不一致的,有没有人有一些想法?

解决方案

当在开关语句中使用时,即使隐式解开
可选项也不会自动解开 。 (原因可能是你
无法与 nil 匹配。)



所以你必须解开(强制使用
color!如果 colors == nil 或与可选绑定),或 - 或者 - 匹配 .Red?
这是的快捷方式.Some(.Red)

  var colors:Colors! 

开关颜色{
case .Red ?:
break //颜色为.Red
默认值:
break //颜色为.White,。黑色或零
}

同样适用于其他模式匹配表达式,例如



  if case .Red? = color {
//颜色是.Red
} else {
//颜色是.White,.Black或nil
}

这与枚举类型无关,只有在模式中隐式使用
展开的可选项:

  let x:Int! = 1 

switch x {
case nil:
break // x is nil
case 1 ?:
break // x is 1
默认值:
break // x是其他数字
}


I have notice weird swift behaviour, because in my opinion colours variable shouldn't be force unwrapped in case of switch written below, but without unwrapping compiler shows me an error message.

enum Colours: Int {
case Red = 0, White, Black
}

var colours: Colours!
colours = .Red

switch colours! { // <-- why I have to unwrap colours? As you can see colours are declared as '!'
case .Red: break
default: break
}

if colours variable is not unwrapped compiler shows me that error:

in my opinion it is swift inconsistency, does anyone have some ideas?

解决方案

When used in a switch statement, even implicitly unwrapped optionals are not automatically unwrapped. (A reason might be that you could not match them against nil otherwise.)

So you have to unwrap (either forcibly with colours! which will crash if colours == nil, or with optional binding), or – alternatively – match against .Red? which is a shortcut for .Some(.Red):

var colours: Colours!

switch colours {
case .Red?:
    break    // colours is .Red
default:
    break    // colours is .White, .Black or nil
}

The same holds for other pattern-matching expressions, e.g.

if case .Red? = colours {
    // colours is .Red 
} else {
    // colours is .White, .Black or nil
}

Also this has nothing to do with enumeration types, only with implicitly unwrapped optionals in a pattern:

let x : Int! = 1

switch x {
case nil:
    break // x is nil
case 1?:
    break // x is 1
default:
    break // x is some other number
}

这篇关于为什么在枚举和切换的情况下需要打包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆