Skip to content

Commit

Permalink
add toAnyValue method for Dictionary
Browse files Browse the repository at this point in the history
  • Loading branch information
nerzh committed Dec 4, 2020
1 parent ea34e06 commit b92ed8c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 32 deletions.
43 changes: 43 additions & 0 deletions Sources/TonClientSwift/Extensions/Dictionary.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//
// File.swift
//
//
// Created by Oleh Hudeichuk on 04.12.2020.
//

import Foundation

public extension Dictionary {

private func checkAnyValue(_ value: Any) -> AnyValue {
if let value = value as? String {
return AnyValue.string(value)
} else if let value = value as? Int {
return AnyValue.int(value)
} else if let value = value as? Double {
return AnyValue.double(value)
} else if let value = value as? Bool {
return AnyValue.bool(value)
} else if let value = value as? [String: Any] {
var dict: [String: AnyValue] = .init()
for (key, val) in value {
dict[key] = checkAnyValue(val)
}
return AnyValue.object(dict)
} else if let value = value as? [Any] {
var array: [AnyValue] = .init()
for (val) in value {
array.append(checkAnyValue(val))
}
return AnyValue.array(array)
} else {
return AnyValue.nil(nil)
// self = .nil(nil)
// throw DecodingError.typeMismatch(JSONValue.self, DecodingError.Context(codingPath: container.codingPath, debugDescription: "Not a JSON"))
}
}

func toAnyValue() -> AnyValue {
checkAnyValue(self)
}
}
33 changes: 1 addition & 32 deletions Sources/TonClientSwift/Extensions/String.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,39 +60,8 @@ public extension String {

public extension String {

private func checkAnyValue(_ value: Any) -> AnyValue {
if let value = value as? String {
return AnyValue.string(value)
} else if let value = value as? Int {
return AnyValue.int(value)
} else if let value = value as? Double {
return AnyValue.double(value)
} else if let value = value as? Bool {
return AnyValue.bool(value)
} else if let value = value as? [String: Any] {
var dict: [String: AnyValue] = .init()
for (key, val) in value {
dict[key] = checkAnyValue(val)
}
return AnyValue.object(dict)
} else if let value = value as? [Any] {
var array: [AnyValue] = .init()
for (val) in value {
array.append(checkAnyValue(val))
}
return AnyValue.array(array)
} else {
return AnyValue.nil(nil)
// self = .nil(nil)
// throw DecodingError.typeMismatch(JSONValue.self, DecodingError.Context(codingPath: container.codingPath, debugDescription: "Not a JSON"))
}
}

func toAnyValue() -> AnyValue? {
if let dict: [String: Any] = self.toDictionary() {
return checkAnyValue(dict)
}
return nil
self.toDictionary()?.toAnyValue()
}
}

0 comments on commit b92ed8c

Please sign in to comment.