Swift - accessing structs

2019-08-27 21:36发布

问题:

If I have a struct defined like this:

struct Cat {
    static let Siamese = "Siamese"
    static let Tabby = "Tabby"
    static let Fluffy = "Fluffy"

    static func cat () -> [String] {
        return [Siamese, Tabby, Fluffy]
    }
}

Why can't I access it like this?

var cat:Cat = Cat.Siamese //"NSString" is not a subtype of Cat

回答1:

You are trying to assign a String to a variable defined as a Cat. That is why you are getting an error.

All of your static members in your Cat struct are strings, not Cats.

Also, your struct doesn't have any actual members. I think you are intending to have a name property:

struct Cat {
    let name: String

    static let Siamese = Cat(name: "Siamese")
    static let Tabby = Cat(name: "Tabby")
    static let Fluffy = Cat(name: "Fluffy")
}

var cat : Cat = Cat.Siamese

You may be better served with an enum:

enum Cat : String {
    case Siamese = "Siamese"
    case Tabby = "Tabby"
    case Fluffy = "Fluffy"
}

var cat: Cat = .Tabby
println(cat.toRaw()) // "Tabby"