Jason Biondo
Jason Biondo

Reputation: 834

How to access struct values inside of another struct in Swift 4?

I currently have

struct cellData {
    var opened = Bool()
    var title = String()
    var iconName = String()
    var sectionData = [Any]()
}

struct SectionData {
    var subTitle: String
    var iconName: String
}

And in another function I call:

let test = tableViewData[indexPath.section].sectionData[dataIndex]

print(test)

Which outputs:

SectionData(subTitle: "Terms", iconName: "")

How do I access the subTitle value because doing test.subTitle throws the following error:

Value of type 'Any' has no member 'subTitle'

Upvotes: 1

Views: 150

Answers (2)

Daniel Dramond
Daniel Dramond

Reputation: 1598

Change your sectionData array to an array of SectionData like so: var sectionData = [SectionData](). Once you do this, you'll able to access it by calling: tableViewData[indexPath.section].sectionData[dataIndex].subTitle

Upvotes: 0

Shamas S
Shamas S

Reputation: 7549

This is because, in your line var sectionData = [Any](), you have defined the type as Any. So when you access it via tableViewData[indexPath.section], you get back the value as Any.

You should change var sectionData = [Any]() to var sectionData = [SectionData]()

Otherwise, once you get the value from tableViewData[indexPath.section], you can convert to SectionData and then access the value.

Upvotes: 6

Related Questions