Day 81 - 100 Days of Swift

2 minute read

Project 24 (part 2)

Day 81 is the second part of the twenty-fourth project. You review the material you covered yesterday and then he gives you a few challenges to work through on your own. He challenges you to add an extension that adds a prefix to a String, if it doesn’t already have it. He challenges you to add an extension that is a calculated property which returns whether a String is numeric. And he challenges you to add an extension that returns an array of String which is the individual lines of the String it is called on.

The first one is basically just the reverse of one of the extensions we wrote yesterday:

1
2
3
4
5
6
7
8
9
10
11
extension String {

    /// Returns the string, ensuring that it has the given prefix
    func withPrefix(_ prefix: String) -> String {
        guard !self.hasPrefix(prefix) else { return self }
        return prefix + self
    }
}

print("pet".withPrefix("car"))    // prints "carpet"
print("carpet".withPrefix("car")) // prints "carpet"

The second one is a simple matter of checking whether you can initialize a Double from the String. Because this was so simple, I decided to take it a little farther and use one of the techniques from yesterday to check if any of the letters in the String is a number:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
extension String {

    /// Returns true if the whole string is a number
    var isNumeric: Bool {
        return Double(self) != nil
    }

    /// Returns true if any character in the string is a number
    var hasNumeric: Bool {
        return self.contains { Double("\($0)") != nil }
    }
}

print("1.74".isNumeric)         // prints true

print("OneTwo3Four".isNumeric)  // prints false
print("OneTwo3Four".hasNumeric) // prints true

For the third one, I just returned the result of a call to components(separatedBy:):

1
2
3
4
5
6
7
8
9
10
extension String {

    /// Returns an array of strings separated by new lines
    func lines() -> [String] {
        return self.components(separatedBy: .newlines)
    }
}

print("this\nis\na\ntest".lines())
// prints ["this", "is", "a", "test"]

Short and sweet today. Nothing too complex, mostly just looking stuff up in the documentation. I could see some of these extensions being useful at some point though, so I’m glad I took the time to think through them.

You can find my version of this project at the end of day 81 on Github here.