silencefox
silencefox

Reputation: 69

Access Class In A Dictionary - Swift

I am now writing a program involves class and dictionaries. I wonder how could I access a class's values inside a dictionary. For the code below how do I access the test1 value using the dictionary. I have tried using dict[1].test1but it doesn't work.

class test {
var tes1 = 1
}
var refer = test()
var dict = [1:refer]

Upvotes: 1

Views: 137

Answers (2)

ABakerSmith
ABakerSmith

Reputation: 22939

There are a few problems with the line dict[1].test1:

Firstly, the subscript on a dictionary returns an optional type because there may not be a value for the key. Therefore you need to check a value exists for that key.

Secondly, in your class Test you've defined a variable tes1, but you're asking for test1 from your Dictionary. This was possibly just a type-o though.

To solve these problems you're code should look something like this:

if let referFromDictionary = dict[1] {
    prinln(referFromDictionary.test1)
}

Upvotes: 3

Antonio
Antonio

Reputation: 72760

That's because the subscript returns an optional, so you have to unwrap it - and the most straightforward way is by using optional chaining:

dict[1]?.tes1

but you can also use optional binding:

if let test = dict[1] {
    let value = test.tes1
}

Upvotes: 2

Related Questions