swift 3.0.2 给出了雄心勃勃的错误“类型 'bool' 已损坏"; [英] swift 3.0.2 gives ambitious error ''Type 'bool' is broken"

查看:33
本文介绍了swift 3.0.2 给出了雄心勃勃的错误“类型 'bool' 已损坏";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个结构并使用这个

i am using this struct and using this

struct Ride {
  var isRideForNow: Bool!    
}
 var sheduleRide: Ride?
 sheduleRide = Ride()
 sheduleRide?.isRideForNow = false

当我这样使用时它工作正常

When i am using like this it works fine

 if (sheduleRide?.isRideForNow)! {
   //some code
 }

但我不知道为什么下面的代码会给出错误类型'bool'被破坏",即使在这个内部没有可选的链接

But i don't know why below code give the error "Type 'bool' is broken" even there is no optional chaining inside this

 if (sheduleRide!.isRideForNow) {
   //some code
 }

推荐答案

这是一条无用的错误消息——它似乎只出现在 Swift 3.0 到 3.0.2 版本中.问题在于 Swift 并没有隐式地解开可选项,因为它认为您正在尝试进行可选项检查.

It's a useless error message – which appears only to be present in Swift versions 3.0 to 3.0.2. The problem is that Swift is not implicitly unwrapping the optional, as it thinks you're trying to do an optional check.

因此,解决方案如@vacawama 说,就是简单地显式地解开可选项:

The solution therefore, as @vacawama says, is to simply explicitly unwrap the optional:

if sheduleRide!.isRideForNow! {
    // some code
}

(如果 sheduleRideisRideForNownil,当然会崩溃)

(which of course will crash if either sheduleRide or isRideForNow is nil)

然而,在我看来,Swift 并未在这里隐式地解开 IUO 的事实与 SE-0054 - 因为 IUO 应该被视为强选项,它们可以像它们一样进行类型检查,但是否则应该隐式解包.

However, the fact that Swift isn't implicitly unwrapping the IUO here, in my view, is not in line with the IUO behaviour detailed in SE-0054 – in that IUOs should be treated as strong optionals where they can be type-checked as them, but otherwise should be implicitly unwrapped.

在布尔条件中,编译器无法将表达式作为强可选类型进行类型检查,因此实际上它应该被隐式解包.此行为被列为错误并已修复在这个拉取请求中,所以声明:

In a boolean condition, the compiler cannot type-check the expression as a strong optional, therefore really it should be implicitly unwrapped. This behaviour was filed as a bug and fixed in this pull request, so the statement:

if sheduleRide!.isRideForNow {
    // some code
}

现在可以在 Swift 3.1 中正常编译.

now compiles fine in Swift 3.1.

但实际上,如@瓦迪安说,你应该考虑isRideForNow 是否应该是IUO.如果需要延迟初始化(否则不能
成为懒惰),你应该只做一个.

But really, as @vadian says, you should be thinking about whether isRideForNow should be an IUO. You should only make it one if it needs to have delayed initialisation (and can't otherwise
be lazy).

如果你在初始化时给它一个值,那么它可以是非可选的:

If you're giving it a value upon initialisation, then it can be non-optional:

struct Ride {
    var isRideForNow: Bool
}

var sheduleRide = Ride(isRideForNow: false)

这篇关于swift 3.0.2 给出了雄心勃勃的错误“类型 'bool' 已损坏";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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