官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 安达市| 渝北区| 确山县| 河曲县| 驻马店市| 临洮县| 贵定县| 克拉玛依市| 灌云县| 凌海市| 望江县| 新巴尔虎右旗| 蚌埠市| 漳州市| 浑源县| 疏勒县| 丹凤县| 郸城县| 宁蒗| 江达县| 崇州市| 昌图县| 罗定市| 忻州市| 阳新县| 吴忠市| 垣曲县| 花垣县| 基隆市| 芜湖县| 革吉县| 泗水县| 仁怀市| 正阳县| 沙雅县| 山西省| 吉安县| 普兰县| 澳门| 安平县| 托克逊县|