Forked from zackdotcomputer/String+IntRange.swift
Last active
August 30, 2020 17:55
-
-
Save leodabus/12afe5515ecccbf033f8eb1ce101fec6 to your computer and use it in GitHub Desktop.
Range<Int> substring finder for Swift Strings - Unsafe but Simple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// String+IntRange.swift | |
// | |
// Created by Zack Sheppard on 8/30/20. | |
// Copyright © 2020 Zack Sheppard. All rights reserved. | |
// Freely usable under the Apache 2.0 License. | |
// | |
import Foundation | |
/// This extension is freely available at | |
/// https://gist.github.com/zackdotcomputer/9d83f4d48af7127cd0bea427b4d6d61b | |
extension StringProtocol { | |
/// Access the range of the search string as integer indices | |
/// in the rendered string. | |
/// - NOTE: This is "unsafe" because it may not return what you expect if | |
/// your string contains single symbols formed from multiple scalars. | |
/// - Returns: A `Range<Int>` that will align with the Swift String.Index | |
/// from the result of the standard function range(of:). | |
func rangeInt<S: StringProtocol>(of aString: S, options: String.CompareOptions = []) -> Range<Int>? { | |
guard let range = range(of: aString, options: options) else { return nil } | |
let start = distance(from: startIndex, to: range.lowerBound) | |
return start..<start+distance(from: range.lowerBound, to: range.upperBound) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment