如何正确打印结构? [英] How do I correctly print a struct?

查看:22
本文介绍了如何正确打印结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的用户结构中存储一系列存储结构,但无法正确打印.

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)

推荐答案

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

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.

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

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

如果打印代码相当复杂,有时实现Streamable会更好:

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

这篇关于如何正确打印结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆