Substring/Top and tail: Difference between revisions

(Added section for Swift (with some extension function sugar))
Line 1,062:
 
=={{header|Swift}}==
Swift has generic functionality that works not only on strings but any type that conforms to relevant protocols. The first method presented uses generic functions from Swift standard library:
The basic version is shown below, but it is rather ugly.
<lang swift>let txt = "0123456789"
println(dropFirst(txt))
txt.substringFromIndex(advance(txt.startIndex, 1))
println(dropLast(txt))
txt.substringToIndex(advance(txt.endIndex, -1))
println(dropFirst(dropLast(txt)))</lang>
txt.substringWithRange(Range<String.Index>(start: advance(txt.startIndex,1), end: advance(txt.endIndex, -1))) </lang>
{{out}}
<pre>123456789
012345678
12345678</pre>
These functions are generic:
<lang swift>let array = [0,1,2,3,4,5,6,7,8,9]
println(dropFirst(array))
println(dropLast(array))
println(dropFirst(dropLast(array)))</lang>
{{out}}
<pre>[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]</pre>
The other method is slicing by range subscripting:
<lang swift>let txt = "0123456789"
println(txt[txt.startIndex.successor() ..< txt.endIndex])
println(txt[txt.startIndex ..< txt.endIndex.predecessor()])
println(txt[txt.startIndex.successor() ..< txt.endIndex.predecessor()])</lang>
{{out}}
<pre>123456789
012345678
12345678</pre>
This method is also generic:
<lang swift>let txt = "0123456789"
let array = [0,1,2,3,4,5,6,7,8,9]
 
func sliceDemo <T: Sliceable where T.Index: BidirectionalIndexType> (col: T) {
 
println(col[col.startIndex.successor() ..< col.endIndex])
However it is rather easy to extend the String handling, so with some simple extension methods this could be:
println(col[col.startIndex ..< col.endIndex.predecessor()])
println(col[col.startIndex.successor() ..< col.endIndex.predecessor()])
}
 
sliceDemo(txt)
<lang>extension String {
sliceDemo(array)</lang>
{{out}}
<pre>123456789
012345678
12345678
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[1, 2, 3, 4, 5, 6, 7, 8]</pre>
Another way is mutating the string:
<lang swift>var txt = "0123456789"
txt.removeAtIndex(txt.startIndex)
txt.removeAtIndex(txt.endIndex.predecessor())</lang>
Although the above mutating functions are not part of a generic protocol (yet, as of Swift 1.2), similar functions exist for relevant collection types:
<lang swift>var array = [0,1,2,3,4,5,6,7,8,9]
array.removeAtIndex(0)
array.removeLast()</lang>
The above functions return what they remove.
You can also extend String type and define BASIC-style functions:
<lang swift>extension String {
/** Positive numbers give index from start of text, whilst negative numbers give index from end of text */
func index(index: Int) -> String.Index {
Anonymous user