Swift 一个特色就是有很多的语法糖,初学可能觉得hold不住,实际用的时候倒是挺便利。
基于对此的喜爱,简单转译一篇短文,Empty Strings in Swift。
isEmpty属性Swift中String是字符的结合,遵循Collection协议。因此会有isEmpty的属性,来判断字符串是否为空。
var isEmpty: Bool {get}Collection.swift的具体实现是:
public var isEmpty: Bool {
return startIndex == endIndex
}"Hello".isEmpty // false
"".isEmpty // true不要使用count是否为0的方式来判断,这样会遍历整个字符串,性能差。
有时候的需求是判断字符串是否是空白字符串,因为设计字符编码的问题,通常不好实现。
" " // space
"\t\r\n" // tab, return, newline
"\u{00a0}" // Unicode non-breaking space
"\u{2002}" // Unicode en space
"\u{2003}" // Unicode em space通常的一些做法是,trim左右的空白,然后判断是否为空,但是swift中有更好的方式,可以使用字符的属性, 类似这样。
func isBlank(_ string: String) -> Bool {
for character in string {
if !character.isWhitespace {
return false
}
}
return true
}这样可以实现,但是更优雅的是,使用allSatisfy的方法。
"Hello".isBlank // false
" Hello ".isBlank // false
"".isBlank // true
" ".isBlank // true
"\t\r\n".isBlank // true
"\u{00a0}".isBlank // true
"\u{2002}".isBlank // true
"\u{2003}".isBlank // trueoption类型字符串的判断,也可以写得很优雅。
extension Optional where Wrapped == String {
var isBlank: Bool {
return self?.isBlank ?? true
}
}var title: String? = nil
title.isBlank // true
title = ""
title.isBlank // true
title = " \t "
title.isBlank // true
title = "Hello"
title.isBlank // false