Skip to content

claudetech/swift-box

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Swift box implementation

A box implementation for Swift.

This is useful when some values can contain errors, for example when fetching some model from an API.

Installation

Add

pod 'SwiftBox'

to your PodFile.

Usage

You can create a Box by using

let fullBox = Box<String>("foo")
let failureBox = Box<String>(NSError(domain: "foo", code: 2, userInfo: nil)) // will be failure
let emptyBox = Box<String>.Empty

You can then use your box:

if box.isFull() {
	let myString = box>! // == box.value!
}
if box.isFailure() {
	let myError = box.failure!
}

if let str = box.value {
	useMyString(str)
}

switch box {
case Box.Full(let wrappedStr):
    useMyString(wrappedStr.value) // == wrappedStr.v
case Box.Failure(let err):
    handleError(err)
case Box.Empty:
    break
}

Example

class User {
    var name: String
    
    init(_ name: String) {
        self.name = name
    }
}

class MyClass {
    var user: Box<User>
    
    init() {
        self.user = Box.Empty
    }
    
    func showUser(u: User) {
        // do something
    }
    
    func handleError(err: NSError) {
        // handle your error
    }
    
    func tryShowUser() {
        switch user {
        case Box.Full(let wrappedUser):
            showUser(wrappedUser.value) // == wrappedUser.v
        case Box.Failure(let err):
            handleError(err)
        case Box.Empty:
            break
        }
    }
}

About

A box implementation for Swift

Resources

License

Stars

Watchers

Forks

Packages

No packages published