- 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.
推薦閱讀
- 現(xiàn)代C++編程:從入門到實(shí)踐
- Learning Scala Programming
- LabVIEW Graphical Programming Cookbook
- Java Web基礎(chǔ)與實(shí)例教程(第2版·微課版)
- 趣學(xué)Python算法100例
- Java程序員面試算法寶典
- Mastering AndEngine Game Development
- 深度強(qiáng)化學(xué)習(xí)算法與實(shí)踐:基于PyTorch的實(shí)現(xiàn)
- RESTful Java Web Services(Second Edition)
- C語(yǔ)言程序設(shè)計(jì)與應(yīng)用(第2版)
- Data Science Algorithms in a Week
- 精通Spring:Java Web開(kāi)發(fā)與Spring Boot高級(jí)功能
- LabVIEW數(shù)據(jù)采集
- Solr權(quán)威指南(下卷)
- Python數(shù)據(jù)預(yù)處理技術(shù)與實(shí)踐