swift - How do I correctly print a struct? -
i'm trying store array of store structs within users struct, can't 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)
you’re initializing them fine. problem store
struct using default printing, ugly mangled version of struct name.
if make conform customstringconvertible
, should print out nicely:
// swift 1.2, use printable rather customstringconvertible extension store: customstringconvertible { var description: string { // create , return string how // you’d store when printed return name } } let me = users(name: "me", stores: [myfirststore, mysecondstore]) println(me.stores) // prints "[h&m, d&g]"
if printing code quite complex, it’s nicer implement streamable
instead:
extension store: streamable { func writeto<target : outputstreamtype>(inout target: target) { print(name, &target) } }
p.s. convention have types structs start capital letter
Comments
Post a Comment