如何正确打印结构?

时间:2015-06-04 11:33:36

标签: swift struct

我正在尝试在我的用户结构中存储一组商店结构,但我无法正确打印它。

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)

1 个答案:

答案 0 :(得分:11)

你正在初始化它们就好了。问题是你的store结构正在使用默认打印,这是一个丑陋的结构名称版本。

如果你使它符合CustomStringConvertible,它应该很好地打印出来:

// 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]"

如果打印代码非常复杂,有时候更好地实现Streamable

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

P.S。惯例是类似结构的类型以大写字母开头