Skip to content

Commit

Permalink
Adds support for NSDictionary, NSAray, NSValue and NSString
Browse files Browse the repository at this point in the history
  • Loading branch information
PopTo committed Aug 8, 2024
1 parent 53d8b3b commit 6d10475
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions Sources/Yams/Representer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@ extension Array: NodeRepresentable {
}
}

extension NSArray: NodeRepresentable {
/// This value's `Node` representation.
public func represented() throws -> Node {
let nodes = try map(represent)
return Node(nodes, Tag(.seq))
}
}

extension Dictionary: NodeRepresentable {
/// This value's `Node` representation.
public func represented() throws -> Node {
Expand All @@ -65,6 +73,14 @@ extension Dictionary: NodeRepresentable {
}
}

extension NSDictionary: NodeRepresentable {
/// This value's `Node` representation.
public func represented() throws -> Node {
let pairs = try map { (key: try represent($0.0), value: try represent($0.1)) }
return Node(pairs.sorted { $0.key < $1.key }, Tag(.map))
}
}

private func represent(_ value: Any) throws -> Node {
if let representable = value as? NodeRepresentable {
return try representable.represented()
Expand Down Expand Up @@ -187,6 +203,13 @@ extension Float: ScalarRepresentable {
}
}

extension NSValue: ScalarRepresentable {
/// This value's `Node.scalar` representation.
public func represented() -> Node.Scalar {
return .init(floatFormatter.string(for: self)!.replacingOccurrences(of: "+-", with: "-"), Tag(.float))
}
}

private func numberFormatter(with significantDigits: Int) -> NumberFormatter {
let formatter = NumberFormatter()
formatter.locale = Locale(identifier: "en_US")
Expand Down Expand Up @@ -258,6 +281,14 @@ extension String: ScalarRepresentable {
}
}

extension NSString: ScalarRepresentable {
/// This value's `Node.scalar` representation.
public func represented() -> Node.Scalar {
let scalar = Node.Scalar(String(self))
return scalar.resolvedTag.name == .str ? scalar : .init(String(self), Tag(.str), .singleQuoted)
}
}

extension UUID: ScalarRepresentable {
/// This value's `Node.scalar` representation.
public func represented() -> Node.Scalar {
Expand Down

0 comments on commit 6d10475

Please sign in to comment.