HIEPING
HIEPING

Reputation: 301

Swift, how can I get a property

I tried to have a string property show different languages by if condition. The last statement shows error! How can I get the member value?

struct EN {
    let hello = "Hello!"
}

struct CN {
    let hello = "Hi!"
}

var stringObj:Any?

var language = "CN"

if language == "EN" {
    stringObj = EN()
}

if language == "CN" {
    stringObj = CN()
}

print(stringObj!)   // "CN(hello: "Hi!")\n"  on playground

print(stringObj!.hello) // error! has no member "hello"

Upvotes: 0

Views: 54

Answers (1)

Palle
Palle

Reputation: 12109

As you have declared stringObj with the type Any?, the Swift compiler has no idea what its actual type is or what properties it has.

If both types CN and EN have a common property, you can use a protocol to specify this:

protocol Language {
     var hello: String { get }
}

struct EN: Language {...}
struct CN: Language {...}

var stringObj: Language?

...

Upvotes: 3

Related Questions