Swift不可变结构和方便的更新

时间:2016-08-22 06:57:06

标签: swift struct

我有一个结构

struct Offer {
    let offerId: Int
    let title: String
    let description: String
    let phoneNumber: String
    let address: String
    let createdAt: NSDate
    let price: Float
    let type: String
    let quantity: Int
    let instructions: [String]
    let votesCount: Int
    let featured: Bool
    let published: Bool
    let publishable: Bool
    let voted: Bool
    let user: PublicProfile
    let images: [OfferImage2]
    let imageIds: [String: Int]
    let featuredImage: String
    let countries: [String]

    var featuredAt: NSDate?
    var featuredTill: NSDate?
    var publishedAt: NSDate?

我想让它保持不变(尽可能使用let而不是var)但我有一个问题。当我需要更新属性时,我会执行以下操作:

mutating func updateTitle(_title: String) {
        self = Offer(offerId: offerId, title: _title, description: description, phoneNumber: phoneNumber, address: address, createdAt: createdAt, price: price, type: type, quantity: quantity, instructions: instructions, votesCount: votesCount, featured: featured, published: published, publishable: publishable, voted: voted, user: user, images: images, imageIds: imageIds, featuredImage: featuredImage, countries: countries, featuredAt: featuredAt, featuredTill: featuredTill, publishedAt: publishedAt)
}

它有效,但我正在寻找更紧凑的方法来做到这一点。

1 个答案:

答案 0 :(得分:2)

您的请求存在一个小问题:

  

我想让它保持不变

不要同意:

  

当我需要更新房产时

如果你的意思是你不想允许从外面改变这个属性,那么就会有更优雅的方式。

您可以制作二传手private

Offer.swift 您可以在任何地方设置标题):

struct Offer {
    let offerId: Int
    private(set) var title: String

    mutating func updateTitle(title: String) {
        self.title = title
    }
}

OtherClass.swift 您不允许设置标题):

    var offer = Offer.init(offerId: 123, title: "Offer1")
    offer.title = "Offer2" //- Compilation error "Cannot assign to property: 'title' setter is inaccessible"