- Swift 4 Programming Cookbook
- Keith Moon
- 191字
- 2021-07-08 10:21:25
There's more...
Class objects are reference types that refer to the way they are stored and referenced internally. To see how these reference type semantics work, consider the following code:
class MovieReview {
let movieTitle: String
var starRating: Int // Rating out of 5
init(movieTitle: String, starRating: Int) {
self.movieTitle = movieTitle
self.starRating = starRating
}
}
// Write a review
let shawshankReviewOnYourWebsite = MovieReview(movieTitle: "Shawshank Redemption", starRating: 3)
// Post it to social media
let reviewLinkOnTwitter = shawshankReviewOnYourWebsite
let reviewLinkOnFacebook = shawshankReviewOnYourWebsite
print(reviewLinkOnTwitter.starRating) // 3
print(reviewLinkOnFacebook.starRating) // 3
// Reconsider my review
shawshankReviewOnYourWebsite.starRating = 5
// The change visible from anywhere with a reference to the object
print(reviewLinkOnTwitter.starRating) // 5
print(reviewLinkOnFacebook.starRating) // 5
We created a review object and assigned that review to two separate constants. As an object is a reference type, it is a reference to the object that is stored in the constant, rather than a new copy of the object. Therefore, when we reconsider our review and rightly give The Shawshank Redemption five stars, we are changing the underlying object, and all references that access that underlying object will see that the starRating property has changed.
推薦閱讀
- DBA攻堅指南:左手Oracle,右手MySQL
- Visual FoxPro程序設計教程
- Oracle從新手到高手
- Interactive Data Visualization with Python
- x86匯編語言:從實模式到保護模式(第2版)
- Learning SQLite for iOS
- Learn Programming in Python with Cody Jackson
- Oracle Database 12c Security Cookbook
- 網絡爬蟲原理與實踐:基于C#語言
- Java高并發編程詳解:深入理解并發核心庫
- Sitecore Cookbook for Developers
- Scala編程(第4版)
- Android開發權威指南(第二版)
- 軟件再工程:優化現有軟件系統的方法與最佳實踐
- Building Microservices with .NET Core 2.0(Second Edition)