Lazy 1.2.0

Lazy 1.2.0

TestsTested
LangLanguage SwiftSwift
License MIT
ReleasedLast Release Nov 2016
SwiftSwift Version 3.0
SPMSupports SPM

Maintained by Nikolai Vazquez.



Lazy 1.2.0

  • By
  • Nikolai Vazquez

Lazy

Save the hard work for later.

The Problem

Swift allows for lazy variables out-of-the-box, however they’re fairly restricted.

  1. They’re only available within a type definition and require a default value that relies on limited surrounding context.

  2. They can’t be referenced from within let constant struct instances.

Lazy solves these two problems by giving you full control over how you want to be lazy. For example, you can declare a Lazy instance anywhere, regardless of scope. You can also use a Lazy value within any type, regardless of instances being constants or not.

Installation

Compatibility

  • Platforms:
    • macOS 10.9+
    • iOS 8.0+
    • watchOS 2.0+
    • tvOS 9.0+
    • Linux

  • Xcode 7.3 and 8.0
  • Swift 2.2 and 3.0

Install Using Swift Package Manager

The Swift Package Manager is a decentralized dependency manager for Swift.

  1. Add the project to your Package.swift.

    import PackageDescription
    
    let package = Package(
        name: "MyAwesomeProject",
        dependencies: [
            .Package(url: "https://github.com/nvzqz/Lazy.git",
                     majorVersion: 1)
        ]
    )
  2. Import the Lazy module.

    import Lazy

Install Manually

Simply add the Lazy.swift file into your project.

Usage

Evaluating

A lazy value is evaluated the first time its contained value is referenced.

If you need to evaluate a lazy value without getting it, you can do so with the evaluate() method.

Checking Evaluation

Not sure if a lazy value has been evaluated just yet? Simply check wasEvaluated!

let lazyInt = Lazy(1)
print(lazyInt.wasEvaluated)  // false
let someInt = lazyInt.value
print(lazyInt.wasEvaluated)  // true

Number Operations

Lazy allows you to be very laid back with numerical operations.

let meaningOfLife = Lazy(8) * 5 + 2
let result = meaningOfLife.value  // 42

Shorthand Operations

If you’re tired of using Lazy(...) around your values, there’s the ~ postfix operator at your disposal.

Similar to ~, the * postfix operator acts as shorthand for obtaining a contained value.

These can be used in combination with each other for ultimate laziness:

Lazy("I should sleep in today!")*.uppercased()~  // "I SHOULD SLEEP IN TODAY!"

License

Lazy is released under the MIT License.