在Swift 4.2中,“错误”方法失败,并显示错误:对象中的键无效。更改项目名称后,它给出了错误。代码是:
GreenGrocer.swift:
import UIKit
private let reuseIdentifier = "grocerItem"
private let screenWidth = UIScreen.main.bounds.width
class ViewController: UIViewController, UICollectionViewDataSource,
UICollectionViewDelegate {
@IBOutlet weak var quantityStepper: UIStepper!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var balanceLabel: UILabel!
@IBOutlet weak var quantityLabel: UILabel!
let greenGrocer: GreenGrocerType
var currentSelection: GrocerSelection?
var quantity: Double = 2.0
required init?(coder aDecoder: NSCoder) {
do {
// decoupled
let dictionary = try PlistConverter.dictionaryFromFile(resource:
"GrocerInventory", ofType: "plist")
let inventory = try
InventoryUnarchiver.grocerInventoryFromDictionary(dictionary:
dictionary)
self.greenGrocer = GreenGrocer(inventory: inventory)
} catch let error {
fatalError("\(error)")
}
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionViewCells()
setupViews()
}
可能是由于项目图标名称的更改或类似原因而失败。 ViewController.swift:
import Foundation
import UIKit
// requirements
protocol GreenGrocerType {
var selection: [GrocerSelection] { get }
var inventory: [GrocerSelection: ItemType] { get set }
var amountDeposited: Double { get set }
init(inventory: [GrocerSelection: ItemType])
func grocer(selection: GrocerSelection, quantity: Double) throws
func itemForCurrentSelection(selection: GrocerSelection) -> ItemType?
func deposit(amount: Double)
}
protocol ItemType {
var price: Double { get }
var quantity: Double { get set }
}
// error types
enum InventoryError: Error {
case InvalidResource
case ConversionError
case InvalidKey
}
enum GrocerError: Error {
case InvalidSelection
case OutOfStock
case InsufficientFunds(required: Double)
}
// helper classes
class PlistConverter {
class func dictionaryFromFile(resource: String, ofType type:String)
throws -> [String: AnyObject] {
guard let path = Bundle.main.path(forResource: resource, ofType: type)
else {
throw InventoryError.InvalidResource
}
guard let dictionary = NSDictionary(contentsOfFile: path), let
castDictionary = dictionary as? [String: AnyObject] else {
throw InventoryError.ConversionError
}
return castDictionary
}
}
class InventoryUnarchiver {
class func grocerInventoryFromDictionary(dictionary: [String:
AnyObject]) throws -> [GrocerSelection: ItemType] {
var inventory: [GrocerSelection: ItemType] = [:]
for (key, val) in dictionary {
if let itemDict = val as? [String: Double], let price =
itemDict["price"], let quantity = itemDict["quantity"] {
let item = GrocerItem(price: price, quantity: quantity)
guard let key = GrocerSelection(rawValue: key) else {
throw InventoryError.InvalidKey
}
inventory.updateValue(item, forKey: key)
}
}
return inventory
}
}
我什么都没找到,或者我误会了什么?