How do I correctly print a struct?

前端 未结 1 449
失恋的感觉
失恋的感觉 2021-01-21 04:37

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 = \"\"
    v         


        
相关标签:
1条回答
  • 2021-01-21 05:26

    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

    0 讨论(0)
提交回复
热议问题