-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathString+Extensions.swift
More file actions
52 lines (40 loc) · 1.32 KB
/
String+Extensions.swift
File metadata and controls
52 lines (40 loc) · 1.32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//
// String+Extensions.swift
//
// https://stackoverflow.com/questions/24092884/get-nth-character-of-a-string-in-swift-programming-language/38215613#38215613
// Copyright © 2020 Leo Dabus. All rights reserved.
//
import Foundation
public extension StringProtocol {
subscript(_ offset: Int) -> Element {
self[index(startIndex, offsetBy: offset)]
}
subscript(_ range: Range<Int>) -> SubSequence {
prefix(range.lowerBound + range.count).suffix(range.count)
}
subscript(_ range: ClosedRange<Int>) -> SubSequence {
prefix(range.lowerBound + range.count).suffix(range.count)
}
subscript(_ range: PartialRangeThrough<Int>) -> SubSequence {
prefix(range.upperBound.advanced(by: 1))
}
subscript(_ range: PartialRangeUpTo<Int>) -> SubSequence {
prefix(range.upperBound)
}
subscript(_ range: PartialRangeFrom<Int>) -> SubSequence {
suffix(Swift.max(0, count - range.lowerBound))
}
}
public extension LosslessStringConvertible {
var string: String {
.init(self)
}
}
public extension BidirectionalCollection {
subscript(safe offset: Int) -> Element? {
guard !isEmpty, let i = index(startIndex, offsetBy: offset, limitedBy: index(before: endIndex)) else {
return nil
}
return self[i]
}
}