title: Implementing protocol on closure in Swift
body: <p>I would like to create some functions in my Swift project that can accept either an object, or a closure which returns that object type. I could of course define the same function with multiple signatures in each place, but that's verbose. I also would like to be able to create type-safe lists of these object/object-returning-closures but can't do that without some common type describing both things.</p>
  
  <h1>This is what I would like to do</h1>
  
  <pre><code>typealias StringClosure = () -&gt; String
  
  protocol Stringable {
      func toStringClosure() -&gt; StringClosure
  }
  
  extension String : Stringable {
      func toStringClosure() -&gt; StringClosure {
          return { return self }
      }
  }
  
  extension StringClosure : Stringable {
      func toStringClosure() -&gt; StringClosure {
          return self
      }
  }
  
  func printStringable(a : Stringable) {
      print(a.toStringClosure()())
  }
  
  
  var stringableList : Stringable[] = ["cat", {return "dog"}, "gecko"]
  
  for stringable in StringableList {
      printStringable(stringable)
  }
  </code></pre>
  
  <p>But this does not work, because I can't actually extend my <code>StringClosure</code> type to implement <code>Stringable</code>. I could make <code>stringableList</code> a list of <code>Any</code> types, but that's not type safe.</p>
  
  <h1>The enum solution</h1>
  
  <p>One solution is that I could make an enum type, but that means I have to explicitly annotate everywhere I use these types with the enum, which is lame. That would look like this:</p>
  
  <pre><code>enum StringableEnum {
      case Str(String)
      case Fun(StringClosure)
  }
  
  func printStringableEnum(a : StringableEnum) {
      switch (a) {
      case let .Str(value):
          print(value)
      case let .Fun(value):
          print(value())
      }
  }
  
  var enumList : StringableEnum[] = [.Str("cat"), .Fun({return "dog"}), .Str("gecko")]
  
  for element in enumList {
      printStringableEnum(element)
  }
  </code></pre>
  
  <p>It's not bad, but it requires the user of my API to now know about this enum, and label their parameters with <code>.Str</code> or <code>.Fun</code> every time they call my <code>printStringableEnum</code> function. Not exactly a nice API!</p>
  
  <p>This may be too much to ask of the language, but does anyone have any better ideas?</p>