Update for Swift 4
In Swift 4, String again matches Collection , so you can use dropFirst and dropLast to trim the beginning and end of the lines. The result is of type Substring , so you need to pass this to the String constructor to return a String :
let str = "hello" let result1 = String(str.dropFirst()) // "ello" let result2 = String(str.dropLast()) // "hell"
dropFirst() and dropLast() also take Int to indicate the number of characters to remove:
let result3 = String(str.dropLast(3)) // "he" let result4 = String(str.dropFirst(4)) // "o"
If you specify more characters than the string, the result is an empty string ( "" ).
let result5 = String(str.dropFirst(10))
Update for Swift 3
If you just want to remove the first character and want to change the original string in place, refer to @MickMacCallum's answer. If you want to create a new chain in this process, use substring(from:) . With the extension to String you can hide the ugliness of substring(from:) and substring(to:) to create useful additions to trim the beginning and end of String :
extension String { func chopPrefix(_ count: Int = 1) -> String { return substring(from: index(startIndex, offsetBy: count)) } func chopSuffix(_ count: Int = 1) -> String { return substring(to: index(endIndex, offsetBy: -count)) } } "hello".chopPrefix() // "ello" "hello".chopPrefix(3) // "lo" "hello".chopSuffix() // "hell" "hello".chopSuffix(3) // "he"
Like the dropFirst and dropLast in front of them, these functions will break if there are not enough letters in the String. The burden depends on whether you use it. This is a valid design decision. You could write them to return an option, which then needs to be deployed by the caller.
Swift 2.x
Alas, in Swift 2 , dropFirst and dropLast (the previous best solution) are not as convenient as before. With the extension to String you can hide the ugliness of substringFromIndex and substringToIndex :
extension String { func chopPrefix(count: Int = 1) -> String { return self.substringFromIndex(advance(self.startIndex, count)) } func chopSuffix(count: Int = 1) -> String { return self.substringToIndex(advance(self.endIndex, -count)) } } "hello".chopPrefix() // "ello" "hello".chopPrefix(3) // "lo" "hello".chopSuffix() // "hell" "hello".chopSuffix(3) // "he"
Like the dropFirst and dropLast in front of them, these functions will break if there are not enough letters in the String. The burden depends on whether you use it. This is a valid design decision. You could write them to return an option, which then needs to be deployed by the caller.
In Swift 1.2, you need to call chopPrefix as follows:
"hello".chopPrefix(count: 3) // "lo"
or you can add the underscore _ in function definitions to suppress the parameter name:
extension String { func chopPrefix(_ count: Int = 1) -> String { return self.substringFromIndex(advance(self.startIndex, count)) } func chopSuffix(_ count: Int = 1) -> String { return self.substringToIndex(advance(self.endIndex, -count)) } }