title: Accept a set of types in Swift
body: <p>I am doing a wrapper on top of the keychain. I would like to have a method to store dictionaries. I am using the Codable protocol to encode the objects into Data.</p>
  <p>I actually don't really wan't the code to store any object in the dictionary, since the data could be read / written from several places in the code that may not know the same custom classes (the code is splitted into frameworks). Therefore accepting only raw types (String, Bool, Float, Double, Integer) and if possible arrays or dictionaries of those would be great.</p>
  <p>So my question is: is it possible to specify a method that would accept only dictionaries like [String: Raw] where Raw would be (String| Bool | Float| Double | Integer | [Raw] | [String: Raw])?</p>
  <p>I also tried to have a constraint on Codable (I would put the interdiction to use custom classes in the documentation), with the code:</p>
  <pre class="lang-swift prettyprint-override"><code>func write&lt;T: Codable&gt;(param: [String: T]) {
      print(param)
  }
  
  func read&lt;T: Codable&gt;(of valueType: T.Type, for key: String) -&gt; T {
      // read the data from the keychain
  }
  
  let param: [String: Int] = [
      &quot;key&quot;: 0
  ]
  
  write(param: param)
  let integer = read(of: Int.self, for: &quot;key&quot;)
  </code></pre>
  <p>Is there a better way to implement this? Especially, here I can accept only values with the same type ([String: String], [String, Int] ...), not [String: (AnyObject &amp; Codable)] to have structures with several levels, like:</p>
  <pre class="lang-swift prettyprint-override"><code>let structure: [String: Codable] = [
      &quot;forename&quot;: &quot;John&quot;,
      &quot;name&quot;: &quot;Doe&quot;,
      &quot;location&quot;: [
          &quot;street&quot;: &quot;Brooklyn av&quot;,
          &quot;city&quot;: &quot;New York&quot;
      ],
      &quot;phone&quot;: 0123456789
  ]
  </code></pre>