Package - SDGGiesbrecht/SDGCornerstone

APIs: macOSLinuxiOSwatchOStvOS

SDGCornerstone

SDGCornerstone forms the foundation of the SDG module family. It establishes design patterns and provides general‐use extensions to the Swift Standard Library and Foundation.

הִנְנִי יִסַּד בְּצִיּוֹן אָבֶן אֶבֶן בֹּחַן פִּנַּת יִקְרַת מוּסָד מוּסָד׃
Behold, I establish in Zion a stone, a tested stone, a precious cornerstone, a sure foundation.

                                                                                                    ―⁧יהוה⁩/Yehova

Features

  • Localization tools (compatible with the Swift Package Manager and Linux).
  • User preferences access (compatible with Linux).
  • Platform‐independent access to best‐practice file system locations.
  • Shared instances of value types.
  • Generic pattern matching.
  • Customizable randomization.
  • Arbitrary‐precision arithmetic.
  • Simple API for running shell commands (desktop platforms only).

...and much more.

(For a list of related projecs, see here.)

Importing

SDGCornerstone is intended for use with the Swift Package Manager.

Simply add SDGCornerstone as a dependency in Package.swift:

let package = Package(
    ...
    dependencies: [
        ...
        .Package(url: "https://github.com/SDGGiesbrecht/SDGCornerstone", versions: "0.7.1" ..< "0.8.0"),
        ...
    ]
)

SDGCornerstone can then be imported in source files:

import SDGCornerstone

Example Usage

// ••••••• Localization •••••••

enum ApplicationLocalization : String, Localization {
    case english = "en"
    case français = "fr"
    static let fallbackLocalization = ApplicationLocalization.english
}

// Define
let text = UserFacingText<ApplicationLocalization, Void>({ (localization, _) in
    switch localization {
    case .english:
        return "Hello, world!"
    case .français:
        return "Bonjour, le monde !"
    }
})

// Use
XCTAssertEqual(text.resolved(),
               "Hello, world!")

// ••••••• Preferences •••••••

let preferences = Preferences.applicationPreferences

// Save
preferences["name"].value = "John Doe"
// Load
let loaded: String? = preferences["name"].value?.as(String.self)

XCTAssertEqual(loaded,
               "John Doe")

// ••••••• File System •••••••

let url = FileManager.default.url(in: .applicationSupport, at: "folder/file.txt")
do {
    // Save
    try "Contents".save(to: url)
    // Load
    let loaded = try String(from: url)

    XCTAssertEqual(loaded,
                   "Contents")
} catch let error {
    XCTFail(error.localizedDescription)
}

// ••••••• Shared Values •••••••

class Owner {
    var property: Shared<String>
    init(property: Shared<String>) {
        self.property = property
    }
}

let originalOwner = Owner(property: Shared("original"))
let anotherOwner = Owner(property: originalOwner.property)

anotherOwner.property.value = "changed"
XCTAssertEqual(originalOwner.property.value,
               "changed")

// ••••••• Pattern Matching •••••••

let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let pattern = CompositePattern([
    LiteralPattern([1]), // 1
    ConditionalPattern(condition: { $0.isEven }), // 2
    AlternativePatterns([
        LiteralPattern([30, 40]), // (∅)
        LiteralPattern([3, 4]) // 3, 4
        ]),
    RepetitionPattern(NotPattern(LiteralPattern([5, 7]))), // 5, 6, 7, 8, 9 (...)
    LiteralPattern([10]) // 10
    ])

XCTAssertEqual(numbers.firstMatch(for: pattern)?.range,
               numbers.startIndex ..< numbers.endIndex)

// ••••••• Randomization •••••••

func rollDie() -> Int {
    return Int(randomInRange: 1 ... 6)
}

if rollDie() == 1 ∧ rollDie() == 1 {
    print("Snake eyes!")
} else {
    print("Not this time...")
}

// ••••••• Arbitrary Precision Arithmetic •••••••

let tenDuotrigintillion: WholeNumber = "10 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000"
XCTAssert(tenDuotrigintillion.isDivisible(by: 10))

#if os(macOS) || os(Linux)

    // ••••••• Shell Commands •••••••

    XCTAssertEqual(try? Shell.default.run(command: ["echo", "Hello, world!"]),
                   "Hello, world!")
#endif

About

The SDGCornerstone project is maintained by Jeremy David Giesbrecht.

If SDGCornerstone saves you money, consider giving some of it as a donation.

If SDGCornerstone saves you time, consider devoting some of it to contributing back to the project.

Ἄξιος γὰρ ὁ ἐργάτης τοῦ μισθοῦ αὐτοῦ ἐστι.
For the worker is worthy of his wages.

                                                                                                    ―‎ישוע/Yeshuʼa

Github

link
Stars: 1

Advertisement

Releases

0.7.1 - Nov 2, 2017

Bug Fixes

  • Solved warnings that appeared when building with Swift 4.0.2.

0.7.0 - Nov 1, 2017

Breaking Changes

  • Many types now support serialization through the Standard Library’s Codable protocol. It is also now a new conformance requirement for several protocols.
  • Number initializers which parse strings now also have throwing counterparts. In protocol requirements, these replace the older, precondition‐failing variants. (The old variants are still usable in most other situations).

New Features

  • New extensions for comparing URLs: is(in:) & path(relativeTo:)
  • All concurrency tools are now available on Linux.

0.6.0 - Oct 8, 2017

Breaking Changes

CGPoint no longer conforms to TwoDimensionalPoint. Because of a nebulous compiler or CoreCraphics bug, this single conformance caused a cascade of abort traps when other modules attempted to link against seemingly unrelated symbols from SDGCornerstone. It will be restored in a future version once the compiler can handle it correctly. In the mean time, you can still apply it in your own module (at your own risk) by merely adding extension CGPoint : TwoDimensionalPoint {}.

0.5.0 - Oct 3, 2017

Breaking Changes

  • Switched to Swift 4.
    • Several obsolete symbols have been removed. In each case, the Swift Standard Library now provides their functionality natively.
      • ExpressibleByTextLiteralsExpressibleByStringLiteral
      • Dictionary
        • merge(with:combine:)merge(_:uniquingKeysWith:)
    • BitwiseLogic has been renamed to BitField.
    • Several protocols from the Swift Standard Library were refactored in Swift 4, so SDGCornerstone’s protocol hierarchies now integrate their refactored equivalents instead. This has various indirect effects on conformance requirements and supplied default implementations. The triggering protocol changes are:
      • AbsoluteValuable → [removed]
      • BitwiseOperations → [removed]
      • SignedNumber
        • Numeric
        • Signed Numeric

0.4.5 - Sep 20, 2017

Bug Fixes

  • Fixed an issue on Linux where permissions interfered with some file operations in the cache directory.