Skip to content

Commit

Permalink
updated func as<T>...
Browse files Browse the repository at this point in the history
  • Loading branch information
TBXark committed Nov 13, 2020
1 parent b6aa779 commit 751355e
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
4 changes: 0 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,6 @@ pod 'JsonMapper', :git=>'https://github.com/TBXark/JsonMapper.git', '~> 1.4.0
```swift
import XCTest
@testable import JsonMapper
final class JsonMapperTests: XCTestCase {
struct Human: Codable {
let age: Int
Expand Down
15 changes: 12 additions & 3 deletions Sources/JsonMapper/JsonMapper.swift
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ public enum JSONElement: Codable, Equatable, Hashable {
}

// MARK: transform
public func `as`<T: Decodable>(type: T.Type = T.self, jsonEncoder: JSONEncoder = JSONEncoder(), jsonDecoder: JSONDecoder = JSONDecoder()) throws -> T {
public func `as`<T: Decodable>(_ type: T.Type = T.self, jsonEncoder: JSONEncoder = JSONEncoder(), jsonDecoder: JSONDecoder = JSONDecoder()) throws -> T {
let data = try jsonEncoder.encode(self)
return try jsonDecoder.decode(T.self, from: data)
}
Expand Down Expand Up @@ -299,8 +299,17 @@ public struct JSONMapper {
}

// MARK: transform
func `as`<T>(_ type: T.Type = T.self) -> T? {
return originData.flatMap({ $0 as? T })
public func `as`<T: Decodable>(_ type: T.Type = T.self, jsonEncoder: JSONEncoder = JSONEncoder(), jsonDecoder: JSONDecoder = JSONDecoder()) -> T? {
guard let value = originData else {
return nil
}
if let v = value as? T {
return v
} else if let json = try? JSONElement(unknownValue: value, jsonDecoder: jsonDecoder) {
return try? json.as(T.self, jsonEncoder: jsonEncoder, jsonDecoder: jsonDecoder)
} else {
return nil
}
}

// MARK: subscript
Expand Down

0 comments on commit 751355e

Please sign in to comment.