Safety In Swift | Fun Time

Let’s say we have a Car and we want it to be safe so we have seatbelts and airbags and we don’t want to let the truck drive unless safety points passed.

Code Sample

enum Safety {
    case seat
    case door
    case airbag
}

struct Car {
    var seatBeltEnabled: Bool
    var doorLocked: Bool
    var airBagsWorking: Bool
}

extension Car   {
    func drive() throws {
        guard seatBeltEnabled else {
            throw Safety.seat
        }

        guard doorLocked else {
            throw Safety.door
        }

        guard airBagsWorking else {
            throw Safety.airbag
        }
        //Everything fine.... drive carefully
    }
}

I hope everything is looking fine so that’s the beauty of Swift otherwise in other approaches we need to manage it with if-else before we start driving.
That’s all about the small beautiful thing I learned today.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s