美文网首页
Swift 中的空字符串

Swift 中的空字符串

作者: linbj | 来源:发表于2019-06-09 14:34 被阅读0次

如何判断一个字符串是空? 这取决于你所说的“空”。可能意味着零长度的字符串,或者是一个可选的字符串也就是 nil。什么是“空白”只包含空格的字符串。让我们看看如何测试这几种情况。

用 【 isEmpty】

Swift 的 String 是一个字符的集合,Collection protocol 已经有一个用来判断空的方法:

var isEmpty: Bool { get }

Collection.swift 源码中可以找到

public var isEmpty: Bool {
  return startIndex == endIndex
}

如果 startIndex 和 endIndex 相同,那么就是空,可以利用这个来判空:

"Hello".isEmpty  // false
"".isEmpty       // true

Note: 用 “count”来判断空,它是遍历了整个string

// 不要这样去判断空
myString.count == 0

空格呢?

有时候想测试空格的string,例如,我想做如下测试看看是否返回true:

" "        // space
"\t\r\n"   // tab, return, newline
"\u{00a0}" // Unicode non-breaking space
"\u{2002}" // Unicode en space
"\u{2003}" // Unicode em space

有人通过判断字符是不是空白从而判断文字是否是空的。Swift 5中,我们可以利用为空白字符属性直接测试。我们可以编写这样的例子:

func isBlank(_ string: String) -> Bool {
  for character in string {
    if !character.isWhitespace {
        return false
    }
  }
  return true
}

这是有用的,用 【allSatisfy】更加简单简单的。给【String】添加一个扩展:

extension String {
  var isBlank: Bool {
    return allSatisfy({ $0.isWhitespace })
  }
}
  @inlinable
  public func allSatisfy(
    _ predicate: (Element) throws -> Bool
  ) rethrows -> Bool {
    return try !contains { try !predicate($0) }
  }
"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

可选的字符串呢?

给可选类型的字符串添加一个扩展:

extension Optional where Wrapped == String {
  var isBlank: Bool {
    return self?.isBlank ?? true
  }
}

使用可选链和一个默认的 true,如果我们使用的可选的字符串是nil,我们使用例子来测试【 isBlank】属性:

var title: String? = nil
title.isBlank            // true
title = ""               
title.isBlank            // true
title = "  \t  "               
title.isBlank            // true
title = "Hello"
title.isBlank            // false

遍历字符串判断空白还是有问题的,使用【isEmpty】就够了。

翻译自Empty Strings in Swift

相关文章

  • 16-Swift之字符串

    1、什么是字符串? 答:在Swift中,字符串就是 Unicode 字符的序列。 2、字符串的使用 1:创建空的字...

  • Swift 3.x(字符串,数组,字典,元组,可选类型)

    Swift 字符串介绍 OC和Swift中字符串的区别 OC中字符串类型是NSString ,在Swift...

  • 字符串

    数组与字符串转换Swift 字符串转数组: Swift 数组转字符串: 1.反转字符串 2.判断字符串是否为空 3...

  • swift-基础-基本语法2

    字符串 Swift中不用写@ Swift中的字符串不是对象,而是个结构体 Swift中的字符串的性能比OC中高 虽...

  • 字符串 为空判断

    Swift 字符串 为空判断 并返回字符串 func emptyString(_ str :AnyObject...

  • Programming in Swift 编程指南

    Swift 基础篇 Swift 语言基础 Swift 中的字符串和集合 Swift 中的类 Swift 中的结构体...

  • Swift字符串

    字符串简介在OC中定义字符串 @"". Swift中用""(注意点:OC中的字符串是NSString,Swift...

  • Swift 6、字符串的使用

    1、 OC中字符串NSString,在swift中字符串是String 2、 OC中@"",在swift中"" 使...

  • Swift--字符串--02

    字符串基础 字符串在OC与Swift中的区别:在OC中字符串类型是NNString,在Swift中字符串类型是St...

  • iOS swift-字符串

    OC和Swift中字符串的区别 在OC中字符串类型时NSString,在Swift中字符串类型是String OC...

网友评论

      本文标题:Swift 中的空字符串

      本文链接:https://www.haomeiwen.com/subject/hmektctx.html