Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve object lookup #21

Merged
merged 13 commits into from Feb 16, 2016
Merged

Improve object lookup #21

merged 13 commits into from Feb 16, 2016

Conversation

zenangst
Copy link
Owner

This PR adds a new method on Inspectable objects.

It can be used to safely get values via key from any object that conforms to the Inspectable protocol.

Example

do {
  let firstName: String = try taylor.value("firstName")
  let lastName: String? = try taylor.value("lastName")
  let age: Int = try taylor.value("age")
} catch { print(error) }

Implementation

  public func value<T>(key: String) throws -> T {
    let value = Mirror(reflecting: self)
      .children
      .filter { $0.label == key }
      .map { $1 }.first

    guard let objectValue = value as? T else {
      throw MappableError.TypeError(message: "Tried to get value \(value!) for \(key) as \(T.self) when expecting \(types()[key]!)")
    }

    return objectValue
  }

The method throws to make sure that you are getting the correct value type back.

As an added bonus, the error message that the method throws should give you enough information to point you to the right direction of what when wrong when trying to get the value.

Failure example

let age: String = try taylor.value("age")

Would render this error message:

TypeError("Tried to get value 27 for age as String when expecting Int")

@@ -1,6 +1,11 @@
import Foundation
import Sugar

public typealias OptionalString = Optional<String>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zenangst Is it used?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh, I think I used them when going with the other approach, the one where you had object.value("firstName", OptionalString.self). These should be removed now, good catch!

@zenangst
Copy link
Owner Author

Think I'll just merge this an start working on #23. This might change before it's ready for release anyways.

zenangst added a commit that referenced this pull request Feb 16, 2016
@zenangst zenangst merged commit 033ad1b into master Feb 16, 2016
@zenangst zenangst deleted the improve/object-mapping branch February 16, 2016 17:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants