This one I couldn’t get to work quite right without adding something to Asset - a property designed to hold onto the asset’s index in the array. I couldn’t figure out a more elegant way to do it, so I went with the quick-and-dirty method
/// Asset.swift
...
var assetIndex: Int
...
init(name: String, value: Double) {
...
self.assetIndex = 0
}
/// Person.swift
func takeOwnership(of asset: Asset) {
accountant.gained(asset, completion: {
...
asset.assetIndex = assets.endIndex // have to assign the index here. Subtracting 1 because endIndex returns the number AFTER the last index, as if you started at '1'
})
}
/* new function */
func removeOwnership(of asset: Asset) {
accountant.lost(asset, completion: {
asset.owner = nil
assets.remove(at: asset.assetIndex - 1)
})
}
/// Accountant.swift
/* new function */
func lost(_ asset: Asset, completion: () -> Void) {
netWorth -= asset.value
completion()
}
/// main.swift
/* and finally...*/
bob?.takeOwnership(of: laptop!)
bob?.takeOwnership(of: hat!)
bob?.removeOwnership(of: laptop!) // removes asset and its reference
Silver Challenge
This one isn’t too difficult (so maybe I did something wrong?) - all you have to do is check if the owner is nil or not before setting ownership of the asset. Update takeOwnership(of:) accordingly:
func takeOwnership(of asset: Asset) {
if asset.owner == nil {
accountant.gained(asset, completion: {
asset.owner = self
assets.append(asset)
asset.assetIndex = assets.endIndex - 1
})
} else {
print("Item is already owned by \(asset.owner?.name). Remove ownership before you reassign.")
}
}
@macintacos, (love the handle, btw, made me lol) Thanks for posting, I wasn’t able to figure that part out. When I typed your code in, I noticed that the only problem with tracking this index in the asset is that you are then forced to disown the items in the opposite order as you took ownership of them
For example, if you setup the array of assets with 2 items, and first try to disown the 0th item, this will shrink the array to have only one asset, at index==0, and then when you try to remove the other item, since its assetIndex is still 1, you end up trying to remove assets[1], which gives you an index out of array bounds crash. To avoid this, you need to empty with LIFO.
I am not sure how to fix it so that it works, though
The choice of a programming language for your application is one of the most complicated and important decisions, which are taken by the programmer. Because of it, in that article you will be able to see all of the benefits and drawbacks of one of the most popular languages called Swift as well as the comparison of it with much older https://artjoker.net/blog/objective-c-or-swift/