My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more

Useful Swift Extension

Shashank Thakur's photo
Shashank Thakur
·Jul 21, 2018

After working with Swift for some time I found there are lot of things that aren’t there out of the box as with other languages. Following are some extensions that I think are useful for day to day working

Accessing string element by index

extension String {
    subscript(i:Int) ->Character {
        let index = self.index(self.startIndex, offsetBy: i)
        return self[index]
    }
}

Unicode Value for Character

extension Character {
    var unicodeValue: Int {
        get {
            let s = String(self).unicodeScalars
            return Int(s[s.startIndex].value)
        }
    }
}

Character from Int Value

extension Int {
   var character:Character?{
       get {
           let u = UnicodeScalar(self)
           if(u != nil) {return Character(u!)}
           return nil
       }
   }
}

String Subscript with range

extension String {
    subscript (r: Range<Int>) -> String
    {
        get {
            let startIndex = self.index(self.startIndex, offsetBy:r.lowerBound)
            let endIndex = self.index(self.startIndex, offsetBy:r.upperBound)

            return String(self[startIndex..<endIndex])
        }
    }
}

These are some extension I felt like are useful, if you came across a necessary extension I would love to hear/learn about it in comments.