LMAssembly // Introducing StringView Ranges Extension MK2.

Co-authored-by: IsaacXen <blackoutxen@gmail.com>
This commit is contained in:
ShikiSuen 2022-12-28 14:43:16 +08:00
parent 2f98f2cc21
commit 6d874e78d9
1 changed files with 49 additions and 0 deletions

View File

@ -0,0 +1,49 @@
// (c) 2021 and onwards The vChewing Project (MIT-NTL License).
// StringView Ranges extension by (c) 2022 and onwards Isaac Xen (MIT License).
// ====================
// This code is released under the MIT license (SPDX-License-Identifier: MIT)
// ... with NTL restriction stating that:
// No trademark license is granted to use the trade names, trademarks, service
// marks, or product names of Contributor, except as required to fulfill notice
// requirements defined in MIT License.
import Foundation
// MARK: - StringView Ranges Extension MK2
// Credit: Isaac Xen (MK1) & Shiki Suen (MK2)
extension String {
/// UTF-8 TXT
/// - Parameters:
/// - separator:
/// - task:
func parse(
splitee separator: Element,
task: @escaping (_ theRange: Range<String.Index>) -> Void
) {
var startIndex = startIndex
split(separator: separator).forEach { substring in
let theRange = range(of: substring, range: startIndex..<endIndex)
guard let theRange = theRange else { return }
task(theRange)
startIndex = theRange.upperBound
}
}
}
// MARK: - StringView Ranges Extension MK1 Backup (by Isaac Xen)
// This is only for reference and is not used in this assembly.
extension String {
fileprivate func ranges(splitBy separator: Element) -> [Range<String.Index>] {
var startIndex = startIndex
return split(separator: separator).reduce(into: []) { ranges, substring in
_ = range(of: substring, range: startIndex..<endIndex).map { range in
ranges.append(range)
startIndex = range.upperBound
}
}
}
}