【问题标题】:Cannot force unwrap value of non-optional type 'Bool'无法强制展开非可选类型“Bool”的值
【发布时间】:2019-01-29 08:01:18
【问题描述】:

我是 Swift 的新手(使用 Swift 4.1)。我正在学习一些教程来尝试学习语法。在代码行中:

if !message.isSender!.boolValue

我收到一条错误消息:

无法强制解开非可选类型“Bool”的值

我四处浏览,无法找到或找出错误的解决方案。

if !message.isSender!.boolValue {
    cell.messageTextView.frame = CGRect(x: 48 + 8, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 20)

    cell.textBubbleView.frame = CGRect(x: 48, y: 0, width: estimatedFrame.width + 16 + 8, height: estimatedFrame.height + 20)
} else {
    cell.messageTextView.frame = CGRect(x: 48 + 8, y: 0, width: estimatedFrame.width + 16, height: estimatedFrame.height + 20)

    cell.textBubbleView.frame = CGRect(x: view.frame.width - estimatedFrame, y: 0, width: estimatedFrame.width + 16 + 8, height: estimatedFrame.height + 20)
}

【问题讨论】:

  • 这取决于messageisSender 的定义方式。告诉我们。
  • 变量“message”和“isSender”的类型是什么?
  • 你唯一强制解包的是isSender,这是一个非可选的Bool。所以你可能只想要if !message.isSender {
  • 您正在遵循哪些教程告诉您使用boolValue 属性?这在 Swift 中是不寻常的。
  • 欢迎来到 Stack Overflow。发帖前请阅读how to ask。除其他事项外,您应该在发帖后闲逛并回复 cmets。

标签: swift boolean optional


【解决方案1】:

既然已经是 Bool 了,就直接用吧:

if !message.isSender

没有理由解包,它不是编译器告诉你的可选,也没有理由访问boolValue 以获得简单的if

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多