私は、構造体スウィフト不変の構造体と便利な更新
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)
}
これは機能しますが、これを行うにはもっとコンパクトな方法を探しています。
なぜあなたは変えたくないものを作るのですか?構造体は値型ですので、 'title'を' var'と注釈し、それを通常の方法で変異させると、現在のコードと同じようになります。なぜなら、構造体全体が突然変異の際にコピーされるからです。 – Hamish