Nazmul Hasan
Nazmul Hasan

Reputation: 10590

How to make nesting set in swift?

below three set how to make one set? . i mean one nested set

var nameSets : Set<String> = ["Nazmul","Hasan","Prince"]
var countrySets : Set<String> = ["UK","London","Bangladesh"]
var securitys : Set<Int> = [2904,99895,8944]

//work
var addresSets : Set = [nameSet,countrySet] 
//cannot convert value of type '[Any]' to specified type 'Set'
 var addresSets : Set = [nameSet,countrySet,security]
// type 'Any' does not conform to protocol 'Hashable'
var addresSets : Set<Any> = [nameSet,countrySet,security]

Upvotes: 1

Views: 357

Answers (1)

Luca Angeletti
Luca Angeletti

Reputation: 59506

I am not sure about what you are trying to achieve here, however first of all let's clean up your code

let names: Set = ["Nazrul", "Hasan", "Prince"]
let countries: Set = ["UK", "London", "Bangladesh"]
let securities: Set = [2904, 99895, 8944]

We have 2 Set(s) of String and 1 Set of Int.

names and countries

Now let's create a new set which will contain names and countries.

let all: Set = [names, countries]

The inferred type of all is Set<Set<String>>.

names, countries and securities

Let's change how all is populated now

let all: Set = [names, countries, securities]
error: argument type 'Set<_>' does not conform to expected type 'Any'

Now the compiler needs a little help to figure out how all should be defined. The right definition is Set<Set<AnyHashable>> so

let all: Set<Set<AnyHashable>> = [names, countries, securities]

Result

Now all contains the 3 original Set(s).

[
    Set([AnyHashable(99895), AnyHashable(8944), AnyHashable(2904)]),
    Set([AnyHashable("Nazmul"), AnyHashable("Prince"), AnyHashable("Hasan")]),
    Set([AnyHashable("London"), AnyHashable("Bangladesh"), AnyHashable("UK")])
]

Upvotes: 5

Related Questions