|
| 1 | +// Copyright © 2021 Saleem Abdulrasool < [email protected]> |
| 2 | +// SPDX-License-Identifier: BSD-3-Clause |
| 3 | + |
| 4 | +import class Foundation.Scanner |
| 5 | + |
| 6 | +/// A structure that specifies an amount to offset a position. |
| 7 | +public struct Offset { |
| 8 | + // MARK - Initializing Offsets |
| 9 | + |
| 10 | + public init() { |
| 11 | + self = .zero |
| 12 | + } |
| 13 | + |
| 14 | + public init(horizontal: Double, vertical: Double) { |
| 15 | + self.horizontal = horizontal |
| 16 | + self.vertical = vertical |
| 17 | + } |
| 18 | + |
| 19 | + // MARK - Getting the Offset Values |
| 20 | + |
| 21 | + public private(set) var horizontal: Double |
| 22 | + |
| 23 | + public private(set) var vertical: Double |
| 24 | +} |
| 25 | + |
| 26 | +extension Offset: Equatable { |
| 27 | + public static func ==(_ lhs: Offset, _ rhs: Offset) -> Bool { |
| 28 | + return lhs.horizontal == rhs.horizontal && lhs.vertical == rhs.vertical |
| 29 | + } |
| 30 | +} |
| 31 | +extension Offset { |
| 32 | + /// Returns a string formatted to contain the data from an offset structure. |
| 33 | + public static func string(for offset: Offset) -> String { |
| 34 | + return String(format: "{%.17g, %.17g}", offset.horizontal, offset.vertical) |
| 35 | + } |
| 36 | + |
| 37 | + /// Returns an `Offset` structure corresponding to the data in a given string. |
| 38 | + /// |
| 39 | + /// In general, you should use this function only to convert strings that were |
| 40 | + // previously created using the `string(for:)` function. |
| 41 | + public static func offset(for string: String) -> Offset { |
| 42 | + let scanner: Scanner = Scanner(string: string) |
| 43 | + guard scanner.scanCharacter() == "{", |
| 44 | + let horizontal = scanner.scanDouble(), |
| 45 | + scanner.scanCharacter() == ",", |
| 46 | + let vertical = scanner.scanDouble(), |
| 47 | + scanner.scanCharacter() == "}" else { |
| 48 | + return .zero |
| 49 | + } |
| 50 | + return Offset(horizontal: horizontal, vertical: vertical) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +extension Offset { |
| 55 | + /// A `Offset` struct whose horizontal and vertical fields are set to the |
| 56 | + /// value 0. |
| 57 | + public static var zero: Offset { |
| 58 | + Offset(horizontal: 0.0, vertical: 0.0) |
| 59 | + } |
| 60 | +} |
0 commit comments