Resistant Resistant - 1 year ago 51
Swift Question

Issue with types in swift?

I did a Team Treehouse code challenge, and I had an issue that I wanted to ask. Basically I created a func inside an enum that takes the specific case of the enum and initializes a given object. It told me to create it inside the enum, but unfortunately when I do this, I came across some errors. I was able to finish the challenge by doing it outside the enum, but I don't think that was exactly what I was supposed to do.

Anyways, my problem was that when it returned the object UIBarButtonItem, if it was assigned to a constant, the type of the constant is "() -> UIBarButtonItem" or depending on how the switch is setup, it could also come out like "(Button) -> UIBarButtonItem". I'm not really sure what the '->' symbol means in this case. Why does it not completely change into the class? What is going on here? In the tutorial right before this, it seems we did the same exact thing, so I'm not sure why it doesn't work.

enum Button {
case Done(String)
case Edit(String)

func toUIBarButtonItem () -> UIBarButtonItem {
switch self {
case .Done: return UIBarButtonItem(title: "Done", style: .Done, target: nil, action: nil)
case .Edit: return UIBarButtonItem(title: "Plain", style: .Plain, target: nil, action: nil)

let done = Button.Done("Done")
let doneButton = Button.toUIBarButtonItem(done)

This is the code that I am running, not including the UIBarButtonItem class. I hope this is enough information to understand what I am asking.

Answer Source

You are calling the toUIBarButtonItem() method on the Button type instead of a Button instance; this is why it does something special: it returns a curried function, which you then bind to done. The result, however, is still a function.

What you probably mean to do is invoke the method on your done object:

let done = Button.Done("Done")
let doneButton = done.toUIBarButtonItem()

A more in-depth explanation can be found under