Skip to content

Commit

Permalink
Merge pull request #13 from iWECon/uiview-support
Browse files Browse the repository at this point in the history
support resolve UIView/other not json data
  • Loading branch information
iWECon authored Jul 6, 2023
2 parents 8147fa4 + 50011b0 commit f2780d8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 4 deletions.
27 changes: 24 additions & 3 deletions Sources/Lookup/Lookup.swift
Original file line number Diff line number Diff line change
Expand Up @@ -240,13 +240,34 @@ public struct Lookup: Swift.CustomStringConvertible, Swift.CustomDebugStringConv
}
}

private func castValueToString(value: Any) -> String {
if let data = try? JSONSerialization.data(withJSONObject: value, options: .prettyPrinted),
private func jsonToPrettyString(value: Any) -> String? {
if JSONSerialization.isValidJSONObject(value),
let data = try? JSONSerialization.data(withJSONObject: value, options: .prettyPrinted),
let str = String(data: data, encoding: .utf8)
{
return str
}
return "Can not cast value to string"
return nil
}

private func castValueToString(value: Any) -> String {
if let str = jsonToPrettyString(value: value) {
return str
}
// map to string
switch value {
case let dict as Dictionary<String, Any>:
let strDict = Dictionary(uniqueKeysWithValues: dict.map { (key: String, value: Any) in
(key, "\(value)")
})
return jsonToPrettyString(value: strDict) ?? "\(strDict)"

case let arr as [Any]:
return jsonToPrettyString(value: arr) ?? "\(arr)"

default:
return "\(value)"
}
}

public var description: String {
Expand Down
17 changes: 16 additions & 1 deletion Tests/LookupTests/LookupTests.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import XCTest
@testable import Lookup
import Foundation
#if os(iOS)
import UIKit
#endif

enum AnimalType {
case dog, cat
Expand Down Expand Up @@ -244,7 +247,19 @@ final class LookupTests: XCTestCase {
lookup["age"] = "8"
XCTAssertEqual(lookup.age.int, 8)
}

try codable()

#if os(iOS)
func uiView() throws {
let view = UIView()
let lookup = Lookup(["view": view])
XCTAssertEqual(lookup.description, """
{
"view" : "\(view)"
}
""")
}
try uiView()
#endif
}
}

0 comments on commit f2780d8

Please sign in to comment.