TypedContentAccessors

public protocol TypedContentAccessors

Mixin that provides convenience accessors for the content of an optional contained entity.

Allows you to replace the following:

resource.latestData?.content as? String
(resource.latestError?.entity?.content as? [String:AnyObject])?["error.detail"]

…with:

resource.text
resource.latestError?.jsonDict["error.detail"]

You can extend this protocol to provide your own convenience accessors. For example:

extension TypedContentAccessors {
  var doorknob: UIDoorknob {
    return typedContent(ifNone: placeholderKnob)
  }
}

Note that the sample code above is only a convenience accessor. It checks whether the entity already has a UIDoorknob, but does not do any parsing to put a UIDoorknob there in the first place. You’d need to pair this with a custom ResponseTransformer that converts raw doorknob responses to UIDoorknobs.

  • typedContent(ifNone:) Extension method

    A convenience for retrieving the content in this container when you expect it to be of a specific type. For example, if you expect the content to be a UIImage:

    let image = resource.typedContent(ifNone: UIImage(named: "placeholder.png"))
    

    See also

    typedContent()

    Declaration

    Swift

    public func typedContent<T>(ifNone defaultContent: @autoclosure () -> T) -> T

    Return Value

    The content if it is present and can be downcast to a type matching both the ifNone parameter and the inferred return type; otherwise returns ifNone.

  • typedContent(ifNone:) Extension method

    Variant of typedContent(ifNone:) with optional input & output.

    Declaration

    Swift

    public func typedContent<T>(ifNone defaultContent: @autoclosure () -> T?) -> T?
  • typedContent() Extension method

    A variant of typedContent(ifNone:) that infers the desired type entirely from context, and returns nil if the content is either not present or cannot be cast to that type. For example:

    func showUser(_ user: User?) {
      ...
    }
    
    showUser(resource.typedContent())  // Infers that desired type is User
    

    Declaration

    Swift

    public func typedContent<T>() -> T?
  • jsonDict Extension method

    Returns content if it is a dictionary with string keys; otherwise returns an empty dictionary.

    Declaration

    Swift

    public var jsonDict: [String : Any] { get }
  • jsonArray Extension method

    Returns content if it is an array; otherwise returns an empty array.

    Declaration

    Swift

    public var jsonArray: [Any] { get }
  • text Extension method

    Returns content if it is a string; otherwise returns an empty string.

    Declaration

    Swift

    public var text: String { get }