Mobile - - By Josh Marchello

Sourcehunt – Swift Edition – March 2017

In continuation of Swift Month, this Sourcehunt is full of Swift goodness. We’ll show you packages for manipulating strings, creating re-usable styles, displaying user avatars, and bringing the awesomeness of FontAwesome to iOS. We’ve also got a package for parsing JSON like a boss, and user authentication for your next (or first!) Vapor app. Did I mention it’s all in Swift!

ArtSabintsev/Guitar[350 ★]

Inspired by JavaScript’s Voca library, this package makes working with strings a cinch. It adds some helpful methods to the String class that let you do anything from change case to add padding.

Let’s say I have an app that takes a filename as input from the user. I want to make sure that filename does not have any spaces or capitalized words in it. Thanks to Guitar, I can do this easily.

var filename = "Deathstar Plans.pdf"

if !filename.isAlphanumeric() {
    filename = filename.snakeCased().lowercased()
}

print(filename) // -> deathstar_plans.pdf

There’s a lot more that this library can do, and there’s still some features yet to be implemented. So whether you need to do some string magic or just want to help out, look no further than Guitar!


psharanda/Atributika[70 ★]

Sticking with strings for a moment, here is Atributika. Let’s say you’re writing a social app where your users can add hashtags anywhere in their posts. You would like to style those hashtags so that they stand out from the rest of the text. Atributika makes this simple. It allows you to define style rules for styling your strings. Below I’ve created a style rule for hashtags:

let myString = "Vader told me he's my dad today! I'm totally freaking out! #confused #shouldastayedondagoba"

let formattedText = myString.styleHashtags(                       
    Style.foregroundColor(Color.blue).font(.systemFont(ofSize: 15))
).attributedString

which produces this:

Atributika hashtag text

Atributika can also parse custom HTML markup allowing you to easily style text and reuse styles throughout your app. Here’s an example of defining some custom styles with Atributika:

let e = Style.font(.italicSystemFont(ofSize: 14))
let hl = Style.backgroundColor(Color.green)

And here I can use my styles to produce a fancy attributed string full of wisdom:

let myString = "<e>Do</e>, or <e>do not</e>. <hl>There is no try.</hl>".style(tags: e, hl).attributedString

Which looks like this:

Atributika styled text

One way to better leverage the power of this library would be to define all your styles in one service object. This object could then be used as an attributed string factory that you pass strings through. This allows you to keep all your styles in one place and use them throughout your application.


ayushn21/AvatarImageView[173 ★]

This package is especially useful when working on a social application. AvatarImageView provides a special UIImageView for displaying user profile pictures. If the user does not have a picture, the AvatarImageView displays the user’s initials. All you need is a data source that conforms to the AvatarImageViewDataSource protocol, like so:

struct MyUser: AvatarImageViewDataSource {
    var name = "Han Solo"
}

This object can specify several options such as an image, specific initials, a background color, etc…

Optionally, you can also include a configuration for things like the shape of the avatar like so:

struct AvatarConfig: AvatarImageViewConfiguration {
    var shape: Shape = .square
}

Then you can feed an AvatarImageView your data source and configuration like so:

myAvatar?.configuration = AvatarConfig()
myAvatar?.dataSource = MyUser()

And just like that, you have an avatar image!

AvatarImageView in action

It may not seem like much, but this package eliminates the need to worry about falling back from a missing image, getting initials, reshaping images, etc…


charles-oder/FontAwesomeSwift [1 ★]

This awesome library brings the awesomeness of FontAwesome to your next awesome swift project! (have I said awesome enough yet?) If you’re unfamiliar with FontAwesome, I would recommend checking it out. It’s a set of vector graphics and CSS that allows you to display and customize icons as if they were text. While the original FontAwesome is primarily for the web, this package brings that same simplicity and customization to iOS, WatchOS, MacOS, etc… Say goodbye to editing icons in Photoshop or GIMP.

The API is simple: create an FASIcon object, style it, and put it where you want it. You can convert your FASIcon into a UIImage or NSAttributedString as well. Here are a couple of examples.

First I’ll make a large UIImage from a FontAwesome icon:

myImageView?.image = FASFontAwesome().userCircleIcon(size: 32).color(color: UIColor.blue).image

Next, I’ll create an attributed string with some icons mixed in for fun

let home: NSAttributedString = FASFontAwesome().homeIcon(size: 17).attributedString
let wifi: NSAttributedString = FASFontAwesome().wifiIcon(size: 17).color(color: UIColor.green).attributedString


let myString: NSMutableAttributedString = NSMutableAttributedString()
myString.append(home)
myString.append(NSAttributedString(string: " is where the ", attributes: nil))
myString.append(wifi)
myString.append(NSAttributedString(string: " connects automatically.", attributes: nil))

myLabel?.attributedText = myString

And here is the end result!

FontAwesomeSwift in Action

Despite its name, this package actually supports several different icon packs such as Material, Ion, and much more. You can even extend it with your own icons!


nodes-ios/Serpent[70 ★]

Next up is a very polished and efficient JSON parser called Serpent. This package is seriously cool. Not only is it extremely fast (they have stats to prove it), but the creators have worked hard to make it very easy to use.

Let’s say I have a struct shaped like this:

struct StormTrooper {
    var name = "FN93847"
    var favoriteColor = "white"
    var shootingRangeScore = "2/457"
}

And I want to pull some StormTroopers from an API. The first thing I must do is teach Serpent what my data looks like and how I’d like it parsed or serialized. To do this, my struct must implement the Serializable protocol, which comes bundled with Serpent. This protocol requires the following methods for data mapping:

extension StormTrooper: Serializable {
    init(dictionary: NSDictionary?) {
        name               <== (self, dictionary, "name")
        favoriteColor      <== (self, dictionary, "favorite_color")
        shootingRangeScore <== (self, dictionary, "shooting_range_score")
    }

    func encodableRepresentation() -> NSCoding {
        let dict = NSMutableDictionary()
        (dict, "name")                 <== name
        (dict, "favorite_color")       <== favoriteColor
        (dict, "shooting_range_score") <== shootingRangeScore
        return dict
    }
}

Now, this is just for three attributes. Writing all this code for larger structures is going to be tedious and time-consuming. Thankfully, the team behind Serpent wrote a small Mac application called Model Boiler that generates this code for you. To use it, copy your struct to the system clipboard and hit cmd+option+6. This populates your clipboard with all the generated code for that struct. Then you can paste it where you want it and make any tweaks if necessary.


stormpath/Turnstile[95 ★]

Finally, if you’re a server-side swifter using Vapor, you’ll find Turnstile particularly interesting. The folks at Stormpath wrote it to manage user authentication in Vapor apps. It uses several objects to track the current user in the application and ensure they are authenticated. It also provides objects for storing the user’s credentials in memory. If you want to store the credentials elsewhere, you can write custom objects called Realms to do so.

Turnstile also facilitates logging through third parties such as Facebook and Google. It’s a robust library written by people who understand authentication.


Each of these great packages can be extremely useful, so go out there and give them some love. Even better, go dig into their source code and submit some PRs. Whether you’re looking for some new tools or a new project to contribute to, you’ve got a great list here. If you’ve found other great libraries that you’d like to share, let us know using the #sourcehunt and #swift tags!

Sponsors