structAlbum{ let title:String let artist:String let year:Int funcprintSummary(){ print("\(title) (\(year)) by \(artist)") } }
let album =Album(title: "呼吸之野", artist: "许嵩", year: 2022) album.printSummary() //输出 呼吸之野 (2022) by 许嵩
要注意的是这里的结构体跟Java的类有区别,是值类型。
1 2 3 4 5 6 7 8 9
//省略结构体 跟上面一样 var album =Album(title: "素颜", artist: "许嵩", year: 2010) var album2 = album album2.addArtist(name: "何曼婷") album.printSummary() album2.printSummary() //输出 //素颜 (2010) by 许嵩 //素颜 (2010) by 许嵩 & 何曼婷
structAlbum{ let title:String var artist:String let year:Int funcprintSummary(){ print("\(title) (\(year)) by \(artist)") } mutatingfuncaddArtist(name : String){ artist ="\(artist) & \(name)" } }
var album =Album(title: "素颜", artist: "许嵩", year: 2010) album.addArtist(name:"何曼婷") album.printSummary() //输出 素颜 (2010) by 许嵩 & 何曼婷
var game =Game() game.score +=10 print("Score is now \(game.score)") game.score -=3 print("Score is now \(game.score)") game.score +=1 print("Score is now \(game.score)") //输出 //Score is now 10 //Score is now 7 //Score is now 8
//借助属性观察器能实现相同的效果 structGame{ var score =0{ willSet{ print("Current Score is \(score)") print("New value is now \(newValue)") } didSet{ print("Score is now \(score)") print("Old value is \(oldValue)") } } }
var game =Game() game.score +=10 game.score -=3 game.score +=1