Mastodon Swift – Josh Hrach

Bindings in SwiftUI

Property wrappers were one of the recent additions to Swift. SwiftUI makes use of several very useful property wrappers. One of them is @Binding. The @Binding property wrapper is really just a convenience for the Binding<T> type.

But before we go into using bindings, what are bindings?

Per Apple’s documentation, a binding connects a property to a source of truth stored elsewhere, instead of storing data directly. You would use a binding to create a two-way connection between a property that stores data, and a view that displays and changes the data.

In SwiftUI, you’ll find this to be a fairly common pattern, especially with built in input fields.

Binding Example

Let’s say we want a view with a switch for the user to interact with. How do we build it?

struct BindingExample: View {
    @State var switchIsOn = false

    var body: some View {
        Form {
            Toggle(isOn: $switchIsOn) {
                Text("Switch 1")
            }
        }
    }
}Code language: PHP (php)

First, we need a mutable variable to hold the state of our switch. In this case, we have a Bool, named switchIsOn. We have to use the @State wrapper so it can be modified in our view.

Next, when we build our Toggle, we need to provide a binding to a property that will hold the state of the toggle. When we pass in the variable, we use the dollar sign to denote that we’re binding to it. So our view holds the current state of switchIsOn, while the Toggle has a binding internally. When the state of the Toggle flips, it is propagated through $switchIsOn back into our view.

Creating a manual binding

If we again look at Apple’s description of a binding, we see that it involves a two-way connection. The binding needs to know the value to get, and where to set the new value when it is changed.

With that knowledge, we can look at how Binding workings. Let’s look at our example again. This time, we’re going to make a binding ourselves.

struct BindingExample: View {
    @State var switchIsOn = false 

    var body: some View {
        Form {  
            Toggle(isOn: Binding(get: {
                self.switchIsOn
            }, set: { newValue in
                self.switchIsOn = newValue
            }) ) {
                Text("Also Switch 1")
            }
        }
    }
}Code language: JavaScript (javascript)

Binding has an initializer that takes a couple of arguments. One, with the get label, is a closure explaining where the binding gets its value. In our example, this is our switchIsOn variable. The other, set, is given the new value for the binding. This gives us the opportunity to do something with it now that it has changed. In our case, we’re setting switchIsOn to the new value.

In its most basic form, Binding opens up a lot of interesting possibilities. In later posts, I’ll talk about when we might want to create a binding between our views, as well as some interesting problems a manual binding can solve.

Property Wrappers in Swift

With Swift 5.1 and Xcode 11, many new features came to Swift. A lot of these were built in to help enable SwiftUI in Apple’s latest OS releases. While diving into SwiftUI is a great way to understand those features, there are some that we don’t need to go into SwiftUI to understand. One of these is property wrappers.

I like to explain property wrappers by a literal definition of the phrase: They wrap properties in functionality. While there are some built into various Apple frameworks (ie SwiftUI), it’s easy to create your own, and they can give you a lot of neat functionality.

How to create a property wrapper

To define a property wrapper, you need to have a custom type (I typically use structs) that you mark as a property wrapper with the @propertyWrapper keyword.

@propertyWrapper
struct Wrapper { 

}Code language: CSS (css)

By adding that attribute, my type now must conform to its requirements. To do so, I need to add a non-static property named wrappedValue. The type of this property will depend on the kind of wrapper you are building. Let’s look at some practical examples and see what we can build.

Easily decoding an ISO 8601 Date

Since Swift 3, we’ve had the very convenient Encodable and Decodable protocols. The type alias Codable is how we typically see it. Having our models conform to Codable allows us to easily encode and decode our models to and from JSON for API communication.

The Date type conforms to Codable. But how does it encode/decode by default?

struct DateTest: Codable {
    var date: Date = Date()
}

let dateTest = DateTest()
let data = try JSONEncoder().encode(dateTest)
let json = try JSONSerialization.jsonObject(with: data, options: [])

print(json)
// {
//    date = "608081487.019236";
// }Code language: JavaScript (javascript)

Okay. At least Date can encode automatically. I can live with that. But it looks like it’s turning a date into a number. What if we want to work with different standard, such as an ISO 8601 Date?

What is an ISO 8601 Date? It a popular date format presented as a string where a date like 10:43 pm on April 4, 2020 would appear like this:
2020-04-08T22:43:30+00:00

So can Date decode this by default? Let’s find out!

let isodateJSON = """
{
    "date": "2012-07-14T01:00:00+01:00"
}
"""

let isoDecodeTest = try JSONDecoder().decode(DateTest.self, from: isodateJSON.data(using: .utf8)!)Code language: PHP (php)

So using a multi-line statement in Swift, I’m going to try and decode an instance of our DateTest struct with this JSON object. Will this work? If you saw how Date encoded itself, then you won’t be surprised by the response we get from trying to decode this JSON.

ERROR: typeMismatch(Swift.Double, 
    Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "date", intValue: nil)], 
    debugDescription: "Expected to decode Double but found a string/data instead.", 
    underlyingError: nil))Code language: JavaScript (javascript)

While we have a valid date format, Date is expecting a Double. What can we do?

We could create a custom JSONDecoder when decoding our type. But if we want to support ISO 8601 dates across various models, then we have to create custom decoders for all of them. That could end up being a lot of manual decoding work. OR… we could create a property wrapper to automatically decode the string coming from our JSON into a valid Date.

We start by creating our property wrapper. Ultimately, we want to provide a Date. So that will be our wrapped type.

@propertyWrapper
struct ISO8601Date {
    var wrappedValue: Date
}Code language: JavaScript (javascript)

This satisfies the basic requirements of @propertyWrapper. Now we have to add our own functionality. In our case, here is where we will build our custom encoding and decoding capabilities.

We start by declaring ISO8601Date itself as conforming to Codable. This will let us wrap properties in a Codable-conforming model and not cause any errors about a model needing to manually provide such conformance.

Next, we create our custom Codable conformance within our ISO8601Date struct.

init(from decoder: Decoder) throws {
    let value = try decoder.singleValueContainer()
    let stringValue = try value.decode(String.self)
    if let date = ISO8601DateFormatter().date(from: stringValue) {
        wrappedValue = date
    } else {
        throw DecodingError.typeMismatch(Date.self, DecodingError.Context(codingPath: [], 
                        debugDescription: "Failed to decode ISO Date. Invalid string format."))
    }
}

func encode(to encoder: Encoder) throws {
    var container = encoder.singleValueContainer()
    
    let string = ISO8601DateFormatter().string(from: wrappedValue)
    try container.encode(string)
}
Code language: JavaScript (javascript)

Our initializer will try and decode a string. If this string can be used to decode a date in the ISO 8601 standard format, it will do so. Otherwise, it will throw an error. Meanwhile, our custom encode function takes the stored date and encodes it into a string using the ISO8601DateFormatter.

Lastly, we add a simple init to allow the user to set a default value with our property wrapper.

init(wrappedValue: Date) {
    self.wrappedValue = wrappedValue
}Code language: JavaScript (javascript)

Put all of this together and what do we get? If we look at our original DateTest model, we can now prepend the @ISO8601Date attribute to our date property and it will encode to and decode from an ISO 8601 string automatically.

struct DateTest: Codable {
    @ISO8601Date var date: Date = Date()
}Code language: JavaScript (javascript)

Using UserDefaults for property storage

You may be using UserDefaults in your app to store simple properties. Perhaps it’s a Bool saying if a user has enabled or disabled some feature. Or perhaps you’re storing a String of the last logged in user. You may have built convenience properties to read and write these values. In doing so, you may have ended up with a pattern like this:

class SettingManager {
    static var userViewedWhatsNew: Bool {
        get {
            UserDefaults.standard.bool(forKey: "userViewedWhatsNew")
        }
        set {
            UserDefaults.standard.set(newValue, forKey: "userViewedWhatsNew")
        }
    }
    
    static var lastLoggedInUser: String? {
        get {
            UserDefaults.standard.string(forKey: "lastLoggedInUser")
        }
        set {
            UserDefaults.standard.set(newValue, forKey: "lastLoggedInUser")
        }
    }
}Code language: JavaScript (javascript)

There’s nothing wrong with the above code (except maybe hard-coded key values). But as you add support for more and more properties, things get to be real tedious. So if we were to abstract this out, what pattern do we see?

For each property, we are both (a) getting the value from UserDefaults and (b) setting the value to UserDefaults using the same (c) key. With this pattern in mind, let’s approach our property wrapper.

@propertyWrapper
struct UserDefault<StoredType> {
    public let key: String

    var wrappedValue: StoredType {
        get {
            UserDefaults.standard.object(forKey: key) as! StoredType
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}Code language: JavaScript (javascript)

Instead of using wrappedValue to store a value we initialize, like in our first example, we have a computed getter and setter. It is performing our reading and writing with UserDefaults. The key used for those transactions? We provide it in our property wrapper.

What data type does this work with? You’ll see that we are using a generic type (StoredType). It will inherit the type from whatever you end up wrapping.

But wait! What if you wrap an optional type, like String?. Won’t the getter crash if there is no object for key? Nope! Because it’s coming back as an optional, or Optional.none case (if you look at how Optionals work in Swift), which is a valid value for something of type String?. But if we did try to read a String that wasn’t there, then it would crash.

So how about we add a default value?

@propertyWrapper
struct UserDefault<StoredType> {
    public let key: String
    public let defaultValue: StoredType

    var wrappedValue: StoredType {
        get {
            UserDefaults.standard.object(forKey: key) as? StoredType ?? defaultValue
        }
        set {
            UserDefaults.standard.set(newValue, forKey: key)
        }
    }
}Code language: JavaScript (javascript)

Now we will attempt to return a value of type StoredType from UserDefaults but, in the event no such object exists, we will return our defaultValue.

How can we use this in our SettingManager above?

class SettingManager {
    @UserDefault(key: "userViewedWhatsNew", defaultValue: false) 
    static var userViewedWhatsNew: Bool    

    @UserDefault(key: "lastLoggedInUser", defaultValue: nil) 
    static var lastLoggedInUser: String?
}Code language: JavaScript (javascript)

If we were to add support for a new property stored in UserDefaults, it is super simple.

Now, notice how we are setting the key and defaultValue properties when declaring our property wrapper. This is making use of the synthesized initializer on our struct. You could make your own init function and use it when declaring the property wrapper.

Summary

Property wrappers are super helpful. They can help you take repeated code and patterns away from your properties and move them into a reusable component. As we’ve seen here, you can make various Codable edge cases easy to solve. They can also help you with code you find yourself repeating in things like a set, didSet, or other such case.

Like other Swift features, property wrappers are just another tool that are worth having in your developer tool box. I hope this post helped demystify them a little bit and make them more approachable for you.

You can find the code for this post in this Github Gist.

Swift Protocols Aren’t Scary

For people new to Swift, or coding in general, there are some keywords that might seem daunting. Optionals. Generics. Sometimes you can explain these in a simple way. Other times, exposure to them might scare learners.

Protocols might seem like a big concept for some. If you look at how many protocols exist in various frameworks, you might think, “Wow, that’s a lot to learn! When will I use all of these?”

For instance, the Int type conforms to 11 different protocols. Do you need to know them all?

What is a protocol?

A protocol is essentially a blueprint. It defines functionality. This can be requiring the existing of certain properties or functions. Something that conforms to a protocol is required to provide the required elements.

For instance, I could declare a protocol that requires the conforming object, whether a class, struct, or enum, to have a name property.

protocol Nameable {
    var name: String { get set }
}Code language: JavaScript (javascript)

If I have a struct representing, say, an instrument, I can have it conform to that protocol, which will require the presence of a name property.

struct Guitar: Nameable {
    var type: String
    
    var name: String // Required because of protocol
}Code language: JavaScript (javascript)

Protocol conformance can be declared when you create your type, or it can be done in an extension. However, extensions cannot contain stored properties, so you can only add support for required functions in extensions.

protocol DataSource {
    func numberOfItems(in section: Int) -> Int
    func dataToShow(at indexPath: IndexPath) -> Data
}

class DataManager {
    // Your class stuff here
}

extension DataManager: DataSource {
    func numberOfItems(in section: Int) -> Int {
        // Return the number of items in each section
    }
    
    func dataToShow(at indexPath: IndexPath) -> Data {
        // Return some data to show for each row/section
    }
}Code language: PHP (php)

When would I use one?

You would use a protocol when you want to require functionality for a type. When would you use this?

With the exception of very basic iOS applications, you are likely to come across a protocol and not even realize it. Consider the following example:

class MyTableViewController: UIViewController {
    
    var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.dataSource = self
        tableView.delegate = self
    }
}

Here, we have a view controller that we’ve created. It has a table view in it. To have a working table view, we need to have a data source and delegate. In simple examples, you would see what we have here: the class itself conforms as a datasource and delegate.

To do that, we’d have to have our class conform to 2 different protocols. One tells the requirements for the data source, the other tells the requirements to be a delegate.

extension MyTableViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return number of rows in each section
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // Return the table view cell for each part of the table view
    }
    
    
}

extension MyTableViewController: UITableViewDelegate {
    // Add support for the delegate methods you want to support
}
Code language: JavaScript (javascript)

So here, we’ve told our class to conform to two protocols so that it can satisfy the requirements of the table view.

They’re just blueprints

When we look at the above example of the UITableView, when it’s looking for something to be a data source, it’s wanting something that conforms to UITableViewDataSource. It’s basically saying, “If you conform to these blueprints, you, too, can be a data source!”

Don’t look at the presence of ALL protocols available to use as daunting. Remember: it’s just saying there are dozens of blueprint options out there. But they’re only used for specific reasons. UITableView wants its data source to conform to a certain protocol. UIScrollView’s delegate has certain requirements.

And what about what you might make? Would you ever want to make a protocol? Sure. If you ever want to require your types have certain properties or functions, you would create your own protocol. You’d basically be drafting your own blueprints in Swift.

That’s all protocols are. Blueprints. They’re not scary at all.

Swift Coding Puzzles #2 – Balanced Brackets

This is part of a series of coding puzzles inspired by the #CodingPuzzle tag/puzzles originally curated and shared by Ali Spittel. This is my approach to solving those puzzles in Swift. If you have any comments or answers you want to share, post them below! I’d love to read them.


Puzzle #2

Given strings of brackets, determine whether each sequence of brackets is balanced.

When would you come across a situation like this? Well, if you ever write a source editor, you might come across something like this. As most programming languages use brackets to denote context, functions, and other divisions, we’ve probably all come across a situation where we forgot to close something off.

For the sake of this exercise, let’s define what brackets mean. In this case, it’ll be three sets of characters: ( ) , [ ] , and { } . The first character we’ll call the “open bracket” and the latter the “close bracket”.

So, what makes a balanced sequence?

  1. A matched pair of brackets.
  2. Any nested brackets must also be matched pairs.

An example of some balanced sequences include: () , [(){}] , {([()])}

An example of some imbalanced sequences include: (() , [([)]] , {([)]}

If any of those become unpaired, then the entire sequence is considered imbalanced. If you’ve ever created a class in Swift and forgot to close a brace when defining functions, you’ll know what that is.

By the above definitions, we can thus determine that in a balanced sequence:

  1. It has an even number of brackets
  2. An open bracket will never meet a close bracket of a different type
  3. A closed bracket will never appear before its corresponding open bracket

That said, here’s how I approached the problem.

First, I defined what each of the brackets were.

let brackets: [Character: Character] = [
    "[":"]",
    "(":")",
    "{":"}"
]
var openBrackets: [Character] { return Array(brackets.keys) as! [Character] }
var closeBrackets: [Character] { return Array(brackets.values) as! [Character] }

Using a dictionary, I’ll be able to easily look up the close bracket for a given open bracket.

Next, let’s look at my function to solve this.

func isBalanced(_ string: String) -> Bool {
    if string.count % 2 != 0 { return false }
    var stack: [Character] = []
    for character in string {
        if closeBrackets.contains(character) {
            if stack.isEmpty {
                return false
            } else {
                let indexOfLastCharacter = stack.endIndex - 1
                let lastCharacterOnStack = stack[indexOfLastCharacter]
                if character == brackets[lastCharacterOnStack] {
                    stack.removeLast()
                } else {
                    return false
                }
            }
        }
        if openBrackets.contains(character) {
            stack.append(character)
        }
    }
    
    return stack.isEmpty
}

First, if the string has an odd number of characters, we automatically fail it. This is in line with point number 1 above.

I then declare a variable to temporarily hold brackets. This stack will be used in the following loop.

Next, we go through each character of the string. Our first check is whether the character is a close bracket or not. If it is, and our stack is empty, it means we’re encountering a close bracket before its open bracket counterpart. We thus return false. If the stack isn’t empty, we check if the last character on the stack is an open counterpart of this close bracket. If it is, we remove the open bracket from the stack. Otherwise, we return false.

If it’s not a close bracket, we’re likely looking at an open bracket. Those automatically get added to the stack.

This loop functions for all characters in the string. Afterwards, our return is whether or not the stack is empty. If it’s not empty, it meant we had more open brackets than closed brackets, and while the earlier catches may not have produced a return, it technically is an unbalanced bracket set.

Here are a few sample calls to this function and their outputs.

isBalanced("()") // True
isBalanced("[]") // True
isBalanced("][") // False
isBalanced("[][") // False
isBalanced("()()") // True
isBalanced("[(){}]") // True
isBalanced("{{[()()][]}}") // True
isBalanced("[]()({)}") // False
isBalanced("(((") // False

I had initially hoped to tackle this with recursion, but I found the above solution to be easier to follow and much easier to manage.

Did you have a different solution? Is there something I could improve with my Swift code? I’d love to hear from you!

Swift Coding Puzzles #1 – Simple Pig Latin

I’ve been following Ali Spittel‘s #CodingPuzzle challenges. While I’ve read most of them, I haven’t actually done them.  But each of them would be a fun little exercise. So, I figured I’d go back and tackle each of them in Swift.

Before I start, a note: There are always multiple ways to tackle coding challenges. This is just my approach to it. If there are better/more optimal ways of doing it, please comment and share your solutions! I’d love to see them. This is as much a way for me to share what I’ve done as it is for me to learn from how others see problems and want to solve them.

That said, here is the first puzzle:

Puzzle #1 – Simple Pig Latin

“Move the first letter of each word to the end of it, then add “ay” to the end of the word. Leave punctuation marks untouched.”

If this was just taking a sentence without punctuation, this would be a lot easier. You could split the array, modify the words, and rebuild the sentence. But keeping punctuation untouched adds a bit of a challenge.

Being me, I also wanted to make sure that this would handle if someone inadvertently misses a space after some punctuation. (No, this likely doesn’t handle apostrophes properly, so contractions will probably not be correct; but I’m no native Pig Latin speaker to know.) So I may have put a little too much thought into this.

First, I wanted to make a function that modifies a word into its proper Pig Latin form.

/// Takes a word and makes it Pig Latinized
func pigLatin(word: String) -> String {
    var newWord = word
    let startIndex = newWord.startIndex
    let firstCharacter = newWord[startIndex]
    newWord.append(firstCharacter)
    newWord.append("ay")
    newWord.remove(at: startIndex)
    return newWord
}

With this function, I can now pass in parts of a sentence as needed. With that done, now I just need to get the words to pass in.

I could have split the array based on space, but that wouldn’t necessarily preserve punctuation. So I instead opted to go through the string character-by-character and parsing words that are found.

func simplePigLatin(_ text: String) -> String {
    let characterSet = CharacterSet.whitespacesAndNewlines.union(.punctuationCharacters)
    var piggyText = ""
    var temporaryWord = ""
    for (index, character) in text.enumerated() {
        let scalar = character.unicodeScalars.first!
        if characterSet.contains(scalar) || index == text.count - 1 {
            if temporaryWord.count > 0 {
                let pigLatinWord = pigLatin(word: temporaryWord)
                piggyText.append(pigLatinWord)
                temporaryWord = ""
            }
            
            // Append any punctuation or white space
            if characterSet.contains(scalar) {
                piggyText.append(character)
            }
        } else {
            // Append letter to temporary word
            temporaryWord.append(character)
        }
    }
    
    return piggyText
}

I go through each character and, if it’s a letter, I add it to a temporary word. If I hit a non-letter (punctuation or whitespace) or the end of the string, I take that temporary word, modify it for authentic Pig Latin, and append it to the return string.

With all of that, here are some sample outputs:

let word = simplePigLatin("I wish I could speak in Pig Latin; I really do!")
print(word) // Iay ishway Iay ouldcay peaksay niay igPay atinLay; Iay eallyray oday!

let contractions = simplePigLatin("I've got day-to-day issues.")
print(contractions) // Iay'evay otgay ayday-otay-ayday ssuesiay.

let badSpacing = simplePigLatin("I forgot,this is not where commas,go")
print(badSpacing) // Iay orgotfay,histay siay otnay hereway ommascay,ogay

So that’s how you can do Pig Latin in Swift. No, it’s not perfect. There are other cases that aren’t dealt with, such as how to handle words starting with vowels or ‘qu’. But I’m no linguist.