// Coordinate.swift
class Coordinate {
var latitude: String
var longitude: String
init(latitude: String, longitude: String) {
self.latitude = latitude
self.longitude = longitude
}
static let defaultCoord: String = "000.000000"
static let zeroCoord: Coordinate = .init(latitude: defaultCoord, longitude: defaultCoord)
// Moved these into this class as they only need to be created once, and can be accessed via the class itself, i.e. Coordinate.validChars
static let validChars: Set<Character> = ["-", ".", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
static let formatIncorrect: String = "May start with a minus and at least 1 number, then a full-stop followed by up to 6 numbers"
// This function validates a coordinate by removing unwanted characters, and making sure there's only one minus sign
static public func validate(_ coord: String) -> String {
var coord_ = coord
// Remove invalid characters
coord_.removeAll(where: { !validChars.contains($0) } )
// If there's more than one minus sign, remove them all and put one at the beginning
// This handles a value like "-12.34-56", transforming it to "-12.3456"
if(coord_.filter( { $0 == "-" } ).count > 1) {
coord_.removeAll(where: { "-".contains($0) } )
coord_ = "-" + coord_
}
// If there's a minus sign, and the first occurrence of it isn't at the beginning
// This handles a value like "12.34-56", transforming it to "-12.3456"
if(coord_.filter( { $0 == "-" } ).count > 0 && coord_.firstIndex(of: "-")! > coord_.startIndex) {
// Remove all the minus signs, and add one to the beginning
coord_.removeAll(where: { "-".contains($0) } )
coord_ = "-" + coord_
}
return coord_
}
}
Topic:
UI Frameworks
SubTopic:
SwiftUI
Tags: