swift - 检查一个 Int 值是否大于或等于另一个 Int?值(value)?

标签 swift macos

<分区>

如何比较两个 Int 值?所以,我有这个:

let limit: Int?
let current: Int = Int(self.stringValue)!

但是当我尝试比较它们时(大于或等于):

  if (current >= self.limit) {
            value = amount
        } else {
            value = current * 10 + amount
            if value > self.max! {
                value = amount
            }

    }

我得到错误:

Binary operator '>=' cannot be applied to operands of type 'Int' and 'Int?'

有什么办法解决这个问题?

最佳答案

因为 limit 是一个可选的 Int (Int?) 它可能是 nil 并且不能直接与 current 进行比较>。因此,首先解包可选以检测和避免处理 nil 情况,并且只比较非 nil 情况。

if let limit = self.limit, current >= limit {
    value = amount
} else {
    value = current * 10 + amount
    if value > self.max! {
        value = amount
    }
}

关于swift - 检查一个 Int 值是否大于或等于另一个 Int?值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49167585/

相关文章:

ios - 将 Swift 字典作为 AnyObject 返回

swift - 安全区域布局指南不适用于 UITableView 的 BackgroundView

objective-c - CG图像记录失真

php - xDebug 似乎安装正常,但无法与 NetBeans 连接

mysql - 更新到 MySQL Workbench 8.0.18 后,未显示任何数据库

windows - 快速创建用于软件测试的全新操作系统安装

xcode - 实时状态栏 View

ios - Swift 4 UIWebView 视频全屏约束错误

ios - UIImagePickerController 在 Swift 3 的图像编辑模式下更改底部栏按钮标题

macos - MacOS M1 上的 Docker kafka 问题停留在配置上