问题
So after updating to iOS 9 and Swift 2 I had many errors in my project that even after clicking the convert automatically option didn't get fixed. Luckily most were pretty simple and I was able to figure them out but I have three major ones left. Is anyone able to help me out with these?
Thanks a lot!
Code chunk #1
override func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject]? {
return attributesList
}
Error for chunk 1
Method does not override any method from its superclass
Code chunk #2
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
Error for chunk 2
A non-failable initializer cannot chain to failable initializer 'init(coder:)' written with 'init?'
Code chunk #3
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
Error for chunk 3
'(NSURLResponse!, NSData!, NSError!) -> Void' is not convertible to '(NSURLResponse?, NSData?, NSError?) -> Void'
EDIT: Now that number three is fixed (but still deprecated) I get this error underneath for this code:
Code:
var dictionary = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary
Error:
Extra argument 'error' in call
回答1:
layoutAttributesForElementsInRect
now returns[UICollectionViewLayoutAttributes]?
not[AnyObject]?
write:override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? { }
Super.init now is fallible
public init?(coder aDecoder: NSCoder)
it means It may return nil so you have to write:required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
Do not use explicit types in this case. Just write:
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in }
Read about error handling because
try!
can let down your app :/try! NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
but sendAsynchronousRequest was deprecated in iOS 9
来源:https://stackoverflow.com/questions/33087478/ios-9-errors-and-correct-conversion-to-swift-2