iOS 9 errors and correct conversion to swift 2

我们两清 提交于 2019-12-23 22:20:10

问题


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:


  1. layoutAttributesForElementsInRect now returns [UICollectionViewLayoutAttributes]? not [AnyObject]? write:

    override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
    }
    
  2. 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)
    }
    
  3. Do not use explicit types in this case. Just write:

    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) in
    
    }
    
  4. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!