如何比较Swift 4.0中String的长度?

问题描述 投票:-1回答:2

在Swift 3中,String的长度可以用作if str.characters?.count >= 2

在Swift 4中,不推荐使用characters.count方法。一个人应该只使用count

但是,在比较if str.count >= 2时,我收到以下错误:

二进制运算符'> ='不能应用于'String.IndexDistance?'类型的操作数(又名'可选')和'国际'

那么我怎样才能进行比较if str.count >= 2

swift string swift4
2个回答
3
投票

这是正确的,在Swift 4中你可以通过.count检查计数而无需访问.characters,但是,看起来字符串是可选的问题,所以你可以做的是可选绑定它:

if let string = str {
     if string.count > 2 // works fine here...
} else {
    // the string is nil...
}

-2
投票

我想你可能会寻找这样的东西:

if let charsize =  str.count as? Int
{
    if (charsize > 3)
    {
        print(charsize)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.