[译]Swift中的空字符串

栏目: Swift · 发布时间: 4年前

内容简介:Swift 一个特色就是有很多的语法糖,初学可能觉得hold不住,实际用的时候倒是挺便利。基于对此的喜爱,简单转译一篇短文,Swift中

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     // true

如何判断Optional的字符串

option类型字符串的判断,也可以写得很优雅。

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

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Probability and Computing

Probability and Computing

Michael Mitzenmacher、Eli Upfal / Cambridge University Press / 2005-01-31 / USD 66.00

Assuming only an elementary background in discrete mathematics, this textbook is an excellent introduction to the probabilistic techniques and paradigms used in the development of probabilistic algori......一起来看看 《Probability and Computing》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具