Model: IPAddressRange: Converting to and from String
This commit is contained in:
parent
945953177e
commit
1d01d1f85d
|
@ -15,6 +15,37 @@ struct IPAddressRange {
|
|||
var networkPrefixLength: UInt8
|
||||
}
|
||||
|
||||
// MARK: Converting to and from String
|
||||
// For use in the UI
|
||||
|
||||
extension IPAddressRange {
|
||||
init?(from string: String) {
|
||||
guard let indexOfSlash = string.lastIndex(of: "/") else { return nil }
|
||||
let indexOfNetworkPrefixLength = string.index(after: indexOfSlash)
|
||||
guard (indexOfNetworkPrefixLength < string.endIndex) else { return nil }
|
||||
let addressString = String(string[string.startIndex ..< indexOfSlash])
|
||||
if let addr = IPv4Address(addressString) {
|
||||
address = addr
|
||||
} else if let addr = IPv6Address(addressString) {
|
||||
address = addr
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
let networkPrefixLengthSubstring = string[indexOfNetworkPrefixLength ..< string.endIndex]
|
||||
if let npl = UInt8(networkPrefixLengthSubstring) {
|
||||
networkPrefixLength = npl
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func stringRepresentation() -> String {
|
||||
return "\(address)/\(networkPrefixLength)"
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: Codable
|
||||
// For serializing to disk
|
||||
|
||||
@available(OSX 10.14, iOS 12.0, *)
|
||||
extension IPAddressRange: Codable {
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
|
|
Loading…
Reference in New Issue