在 Swift 中为 String 添加扩展
xxxixxxx

String extension 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
extension String {
func index(from: Int) -> Index {
// 增加越界防护, 负数就不考虑了吧
if from < count {
return index(startIndex, offsetBy: from)
}
return endIndex
}

func substring(from: Int) -> String {
let fromIndex = index(from: from)
return String(self[fromIndex...])
}

func substring(to: Int) -> String {
String(prefix(to))
}

func substring(with r: Range<Int>) -> String {
let startIndex = index(from: r.lowerBound)
let endIndex = index(from: r.upperBound)
return String(self[startIndex ..< endIndex])
}
}

使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
let str = "01234567"

_ = str.substring(from: 0) // "01234567"
_ = str.substring(from: 4) // "4567"
_ = str.substring(from: 100) // ""


_ = str.substring(to: 0) // ""
_ = str.substring(to: 1) // "0"
_ = str.substring(to: 100) // "01234567"


_ = str.substring(with: 0 ..< 1) // "0"
_ = str.substring(with: 0 ..< 100) // "01234567"
  • Post title:在 Swift 中为 String 添加扩展
  • Post author:xxxixxxx
  • Create time:2021-06-05 15:55:00
  • Post link:https://xxxixxx.github.io/2021/06/05/100-Swift中String扩展/
  • Copyright Notice:All articles in this blog are licensed under BY-NC-SA unless stating additionally.
 Comments