Created
April 29, 2020 07:55
-
-
Save cristhianleonli/7c95a03f8ea01db46390149a00d43751 to your computer and use it in GitHub Desktop.
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
import Foundation | |
public extension String { | |
/// just a wrapper for int type | |
typealias IndexInt = Int | |
/// just a wrapper for int type | |
typealias DistanceInt = Int | |
/** | |
Gets the subtring from start[inclusive] and end index[inclusive] | |
- Parameter start: int index where you want to start substring | |
- Parameter end: int index where you want it stop | |
- Returns: Another string acording limits | |
*/ | |
func substring(start: IndexInt, end: IndexInt) -> String { | |
let startIndex = self.index(self.startIndex, offsetBy: start) | |
var endI: String.Index? | |
if end < 0 { | |
endI = self.index(self.startIndex, offsetBy: self.count + end) | |
} else { | |
endI = self.index(self.startIndex, offsetBy: end + 1) | |
} | |
guard let endIndex = endI else { | |
return "" | |
} | |
return "\(self[startIndex..<endIndex])" | |
} | |
/** | |
Gets the subtring from start[inclusive] and distance | |
- Parameter start: int index where you want to start substring | |
- Parameter distance: int indicating how spaces it should move from start | |
- Returns: Another string acording limits | |
*/ | |
func substring(start: IndexInt, distance: DistanceInt) -> String { | |
return substring(start: start, end: start + distance - 1) | |
} | |
/** | |
Gets the subtring from start[inclusive] to the end of the string | |
- Parameter start: int index where you want to start substring | |
- Returns: Another string acording limits | |
*/ | |
func substring(from: IndexInt) -> String { | |
return substring(start: from, end: self.count - 1) | |
} | |
/** | |
Gets the character at specific position, could be negative | |
- Parameter index: int index where you want the character | |
- Returns: Another string with the character | |
*/ | |
func character(at index: IndexInt) -> String { | |
if index < 0 { | |
if self.count + index < 0 { | |
return "" | |
} | |
return substring(start: self.count + index, distance: 1) | |
} | |
return substring(start: index, distance: 1) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment