在Swift 3中,String的长度可以用作if str.characters?.count >= 2
。
在Swift 4中,不推荐使用characters.count
方法。一个人应该只使用count
。
但是,在比较if str.count >= 2
时,我收到以下错误:
二进制运算符'> ='不能应用于'String.IndexDistance?'类型的操作数(又名'可选')和'国际'
那么我怎样才能进行比较if str.count >= 2
?
这是正确的,在Swift 4中你可以通过.count
检查计数而无需访问.characters
,但是,看起来字符串是可选的问题,所以你可以做的是可选绑定它:
if let string = str {
if string.count > 2 // works fine here...
} else {
// the string is nil...
}
我想你可能会寻找这样的东西:
if let charsize = str.count as? Int
{
if (charsize > 3)
{
print(charsize)
}
}