How do I remove parts of a string and return those removed parts to another string in Swift?
Example:
var myString = "10setembro2017"
let newString = myString.removeAndReturn(index:1..2)
print(myString) //setembro2017
print(newString) //10
How do I remove parts of a string and return those removed parts to another string in Swift?
Example:
var myString = "10setembro2017"
let newString = myString.removeAndReturn(index:1..2)
print(myString) //setembro2017
print(newString) //10
This is a lot more complex than it sounds, but I'll try to explain step by step in detail.
First you need to change the parameter type of your function to ...
which in this case is called CountableClosedRange<Int>
but String
in Swift does not use Int
as index but String.Index
.
To convert Int to index you need to use a method of String
called index(String.Index, offsetBy: Int)
. To convert the start of your subrange you need to pass the startIndex
of your String
and lowerBound
of your range to offset.
Remember that Swift indexes start at zero instead of one.
To convert% of% of your range to% of your subrange, you can offset upperBound
so that you do not double the offset of endIndex
unnecessarily and pass the count property of your range (which is equal the difference of lowerBound
minus lowerBound
).
Then you save the substring of your upperBound
on an object that can be declared as constant and use the removeSubrange method to remove the subrange of your lowerBound
(you need to declare the method as mutating to be able to change its String
).
Finished this is you just return a new String initialized with the substring you saved before removing the subrange.
And to complete String
lets you use this method and dequete the result.
extension String {
@discardableResult
mutating func remove(range: CountableClosedRange<Int>) -> String {
precondition(0..<count ~= range.upperBound, "invalid range")
let lowerBound = index(startIndex, offsetBy: range.lowerBound)
let upperBound = index(lowerBound, offsetBy: range.count)
let subrange = lowerBound..<upperBound
defer { removeSubrange(subrange) }
return String(self[subrange])
}
}
var myString = "10setembro2017"
let range = 0...1
if myString.count > range.upperBound {
let dia = myString.remove(range: range)
print(dia)
print(myString)
}
Note: This is my birthday day :)