Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly print a struct?

Tags:

struct

swift

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)
like image 233
GarySabo Avatar asked Jun 04 '15 11:06

GarySabo


1 Answers

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

like image 127
Airspeed Velocity Avatar answered Nov 04 '22 13:11

Airspeed Velocity