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

Document the use of the alternate operator #285

Open
gfontenot opened this issue Nov 4, 2015 · 5 comments
Open

Document the use of the alternate operator #285

gfontenot opened this issue Nov 4, 2015 · 5 comments

Comments

@gfontenot
Copy link
Collaborator

Related: #284

Our use of Alternative is something that sticks out to me as being insanely powerful, but we don't talk about it ever. We should add some documentation around this. Ideas:

@alskipp
Copy link
Contributor

alskipp commented Mar 16, 2016

Another use for the Alternative operator could be for supplying default values to avoid the use of Optionals in models. Here's a quick example:

struct Player {
  let id: Int, name: String, lives: Int, goldCoins: Int
}

extension Player: Decodable {
  static func decode(j: JSON) -> Decoded<Player> {
    return curry(self.init)
      <^> j <| "id"
      <*> j <| "name" <|> pure("Anonymous Player")
      <*> j <| "lives"
      <*> j <| "goldCoins" <|> pure(0)
  }
}

let playersJSON: AnyObject = [
  ["id": 1, "name": "Gertrude", "lives": 5, "goldCoins": 20],
  ["id": 2, "name": "Dave", "lives": 1],
  ["id": 3, "lives": 3],
  ["id": 4, "lives": 1, "goldCoins": 13],
]


let players: [Player]? = decode(playersJSON)
print(players!)

What do you think? If you thought it a reasonable example then something similar could be added to the included Argo Playground file.

@paulyoung
Copy link
Contributor

I do this when the server might return null instead of an empty array.

@Marcin-Kapusta
Copy link

@paulyoung How are You doing this with Arrays. I've created this Issue I was trying use .success or pure without any success. My goal is similar than Yours. Server returns null for Array and I would like to convert it to just empty Array for not optional Array property.

@paulyoung
Copy link
Contributor

@rob5408
Copy link

rob5408 commented Mar 12, 2017

I don't know about anyone else, but I definitely needed extra parentheses to get this working...

extension Team: Decodable {
    static func decode(_ json: Argo.JSON) -> Decoded<Team> {
        return curry(Team.init)
            <^> (json <| "id" <|> pure("123"))
            <*> (json <| "name" <|> pure("Anonymous"))
    }
}

Without them I got an error "Cannot convert value of type '(Id, Name) -> Team' to expected argument type '(_) -> Team'"

(Swift 3, Argo 4.1.2, Runes 4.0.1, Curry 3.0.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants