Created
February 8, 2018 07:58
-
-
Save aryzae/6ab30face4e2ea506e3524c6e0599564 to your computer and use it in GitHub Desktop.
Swift4 StringのアクセスをsubscriptでIntによって可能にした
This file contains hidden or 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
extension String { | |
/// String[index] | |
/// | |
/// - Parameter i: Index of String | |
public subscript(i: Int) -> String { | |
let index = self.index(startIndex, offsetBy: i) | |
return String(self[index]) | |
} | |
/// String[startIndex..<endIndex] | |
/// | |
/// - Parameter range: CountableRange<Int> (ex. 0..<5) | |
public subscript(range: CountableRange<Int>) -> String { | |
let start = index(startIndex, offsetBy: range.lowerBound) | |
let end = index(startIndex, offsetBy: range.upperBound) | |
return String(self[start..<end]) | |
} | |
/// String[startIndex...endIndex] | |
/// | |
/// - Parameter range: CountableClosedRange<Int> (ex. 0...5) | |
public subscript(range: CountableClosedRange<Int>) -> String { | |
let start = index(startIndex, offsetBy: range.lowerBound) | |
let end = index(startIndex, offsetBy: range.upperBound) | |
return String(self[start...end]) | |
} | |
/// String[startIndex...] | |
/// | |
/// - Parameter range: CountablePartialRangeFrom<Int> (ex. 0...) | |
public subscript(range: CountablePartialRangeFrom<Int>) -> String { | |
let start = index(startIndex, offsetBy: range.lowerBound) | |
return String(self[start...]) | |
} | |
/// String[...endIndex] | |
/// | |
/// - Parameter range: PartialRangeThrough<Int> (ex. ...5) | |
public subscript(range: PartialRangeThrough<Int>) -> String { | |
let end = index(startIndex, offsetBy: range.upperBound) | |
return String(self[...end]) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment