dictionary - Passing swift dictionaries with different value types to same function -


i have 2 dictionaries:

let dict1 = [string : mytype1] let dict2 = [string : mytype2] 

to clarify: mytype1 , mytype2 structs , each dict can have 1 valuetype.

and i'd able pass them same function:

func dosomethingwithdict(dict : [string : anyobject]) {    // dict } 

but gives me error:

cannot convert value of type '[string : mytype1]' expected argument type '[string : anyobject]' 

is there way fix this, possible?

if want sure dictionary declared [string:mytype1] or [string:mytype2] passed function, think best solution declaring protocol

protocol myprotocol {} 

and making mytype1 , mytype2 conform it

struct mytype1: myprotocol { } struct mytype2: myprotocol { } 

now can declare function generic type t must conform myprotocol. declare dict parameter [string:t].

func dosomethingwithdict<t t: myprotocol>(dict: [string: t]) {      guard let value = dict["key"] else { return }      switch value {     case let type1 mytype1: print(type1)     case let type2 mytype2: print(type2)     default: fatalerror()     } } 

this guarantee value of dictionary mytype1 or mytype2.

update

in comment below said want pass no longer dictionary value of mytype1 or mytype2.

in case become easier no longer need generics.

protocol myprotocol {} struct mytype1: myprotocol { } struct mytype2: myprotocol { }  func dosomething(elm: myprotocol) {     switch elm {     case let mytype1 mytype1: print(1)     case let mytype2 mytype2: print(2)     default: fatalerror()     } } 

Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -