Skip to content

Instantly share code, notes, and snippets.

@bhrott
Last active December 30, 2018 00:34
Show Gist options
  • Save bhrott/dd3689253fcb970bd143bb82685a80a4 to your computer and use it in GitHub Desktop.
Save bhrott/dd3689253fcb970bd143bb82685a80a4 to your computer and use it in GitHub Desktop.
Fucking substring Swift 3

1 - Create a extensions for String with a new, wonderfull, superpower method called crop:

extension String {
    func crop(from: Int, length: Int) -> String! {
        let startIndex = self.index(self.startIndex, offsetBy: from)
        
        var result = self.substring(from: startIndex)
        
        let endIndex = result.index(result.startIndex, offsetBy: length)
        result = result.substring(to: endIndex)
        
        return result
    }
}

Now you can rest in peace:

var str = "12345678901"

var result = str.crop(from: 6, length: 3)
// results in "789"
@comm1x
Copy link

comm1x commented Dec 30, 2018

Oh, many thanks. This is real helpful.

Found this gist using search phrase in google: "FUCKING SWIFT HOW TO SUBSTRING STRING"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment