iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Exercises

Small problems to lock in protocols, optionals, and Codable in Swift.

Three short challenges

EXAMPLE
// 1) Optional chaining + nil coalescing
struct User { let name: String?; let email: String? }

func displayName(for u: User) -> String {
    return u.name?.trimmingCharacters(in: .whitespaces) ?? u.email ?? "anon"
}

// 2) Protocol-oriented: a Cacheable conformer
protocol Cacheable {
    associatedtype Key: Hashable
    var cacheKey: Key { get }
}

extension Cacheable {
    func storedIn<C: AnyObject>(_ cache: NSCache<NSString, AnyObject>) -> Self where Key == String {
        cache.setObject(self as AnyObject, forKey: cacheKey as NSString)
        return self
    }
}

// 3) Codable: tolerate missing fields
struct Profile: Codable {
    let id: Int
    let name: String
    let bio: String?

    enum CodingKeys: String, CodingKey { case id, name, bio }
}

let json = #"{ \"id\": 1, \"name\": \"Ada\" }"#.data(using: .utf8)!
let p = try JSONDecoder().decode(Profile.self, from: json)
print(p.bio ?? "no bio")

Why it matters

Optionals are the Swift safety net - lean on them. Codable handles 90 percent of API parsing; reach for custom init only when fields rename or transform.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
// Fill in: func add(_ a: Int, _ b: Int) ____ Int { a + b }
Try it Yourself »

Discussion

Loading…