GarySabo
GarySabo

Reputation: 6690

How do I correctly print a struct?

I'm trying to store an array of store structs within my users struct, but I can't get this to print correctly.

struct users {
    var name: String = ""
    var stores: [store]
}

struct store {
    var name: String = ""
    var clothingSizes = [String : String]()        
}

var myFirstStore = store(name: "H&M", clothingSizes: ["Shorts" : "Small"])
var mySecondStore = store(name: "D&G", clothingSizes: ["Blouse" : "Medium"])

var me = users(name: "Me", stores: [myFirstStore, mySecondStore])
println(me.stores)

Upvotes: 5

Views: 9611

Answers (1)

Airspeed Velocity
Airspeed Velocity

Reputation: 40965

You’re initializing them just fine. The problem is your store struct is using the default printing, which is an ugly mangled version of the struct name.

If you make it conform to CustomStringConvertible, it should print out nicely:

// For Swift 1.2, use Printable rather than CustomStringConvertible 
extension Store: CustomStringConvertible {
    var description: String {
        // create and return a String that is how
        // you’d like a Store to look when printed
        return name
    }
}

let me = Users(name: "Me", stores: [myFirstStore, mySecondStore])
println(me.stores)  // prints "[H&M, D&G]"

If the printing code is quite complex, sometimes it’s nicer to implement Streamable instead:

extension Store: Streamable {
    func writeTo<Target : OutputStreamType>(inout target: Target) {
        print(name, &target)
    }
}

p.s. convention is to have types like structs start with a capital letter

Upvotes: 17

Related Questions