swift - 有没有办法识别数组中的 int 是一位数还是两位数?

标签 swift

是否可以识别数组中的 int 是一位数还是两位数?

例如,这个数组:[2,4,14,77]

array[0] 是一个数字,我会得到一个输出会说它是一个数字, 而 array[2] 是两位数,所以输出会说它是 double 。

人们会怎么做呢?

最佳答案

只需检查数字是否大于 9 或小于 -9。

for n in numArray {
    if n > 9 || n < -9 {
        println("double")
    } else {
        println("single")
    }
}

您甚至可以将其添加为 Int 的扩展以使其更方便:

extension Int {
    func isDouble() -> Bool {
        if self > 9 || self < -9 {
            return true
        } else {
            return false
        }
    } 
}

然后您可以在这样的上下文中使用它"

for n in numArray {
    var digits = (n.isDouble()) ? "double" : "single"
    println("Number \(n) is \(digits)")
}

关于swift - 有没有办法识别数组中的 int 是一位数还是两位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31875159/

相关文章:

ios - 快速键盘听不到输入声音

ios - UITextField 编辑更改不调用

ios - 添加 Google 移动插页式广告 Swift

在更新中多次快速调用函数

swift - 如何在 Swift 中删除 UIButton 的 CALayer 底部边框?

ios - 将原始数据 "AnyObject?"转换为 NSData 或字符串

swift - 将 UIButton 图像更改为另一个 UIButton ImageView

ios - 提交应用程序供审核时使用的登录凭据

ios - 从 xib IBOutlets nil 快速加载 UIViewController

ios - 从 Firebase 存储中删除表格 View 图像