gpt4 book ai didi

swift - 如何正确打印结构?

转载 作者:可可西里 更新时间:2023-10-31 23:56:33 27 4
gpt4 key购买 nike

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

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 结构使用默认打印,这是结构名称的丑陋损坏版本。

如果你让它符合 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)
}
}

附注约定是让结构等类型以大写字母开头

关于swift - 如何正确打印结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30642763/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com