print可直接印出struct的所有屬性

struct很多地方都不如class,比方它不能繼承。然而天生我材必有用,它還是有它可取之處,比方print列印時,struct資料可印出完整的屬性內容,class卻只會印出我們早就知道,沒什麼用的類別名稱。

範例:

struct Baby1 {
var name = “彼得潘”
var age = 18
}
var cuteBaby1 = Baby1()
print(cuteBaby1)
class Baby2 {
var name = “彼得潘”
var age = 18
}
var cuteBaby2 = Baby2()
print(cuteBaby2)

結果:

Baby1(name: “彼得潘”, age: 18)
Baby2

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store