将文件转换为Swift 3:无法在当前上下文中推断闭包类型

时间:2016-10-03 07:13:32

标签: ios swift swift3 infix-notation

我在我的应用中转换了一些库代码,但我无法弄清楚如何将此文件从Swift 2.3转换为Swift 3

LocalidadID  = db.Localidads.Include("Departamento.Provincia.").Where(a=>a.LocalidadId == usuario .LocalidadID)

错误在最后两个函数中。

import UIKit

struct Constraint{
    var identifier: String?

    var attribute: NSLayoutAttribute = .centerX
    var secondAttribute: NSLayoutAttribute = .notAnAttribute
    var constant: CGFloat = 0
    var multiplier: CGFloat = 1
    var relation: NSLayoutRelation = .equal
}

func attributes(attrs:NSLayoutAttribute...) -> [NSLayoutAttribute]{
    return attrs
}

infix operator >>- : MultiplicationPrecedence

func >>- <T: UIView> (lhs: (T,T), apply: (inout Constraint) -> () ) -> NSLayoutConstraint {
    var const = Constraint()
    apply(&const)

    const.secondAttribute = .notAnAttribute == const.secondAttribute ? const.attribute : const.secondAttribute

    let constraint = NSLayoutConstraint(item: lhs.0,
                                        attribute: const.attribute,
                                        relatedBy: const.relation,
                                        toItem: lhs.1,
                                        attribute: const.secondAttribute,
                                        multiplier: const.multiplier,
                                        constant: const.constant)

    constraint.identifier = const.identifier

    NSLayoutConstraint.activate([constraint])
    return constraint
}

func >>- <T: UIView> (lhs: T, apply: (inout Constraint) -> () ) -> NSLayoutConstraint {
    var const = Constraint()
    apply(&const)

    let constraint = NSLayoutConstraint(item: lhs,
                                        attribute: const.attribute,
                                        relatedBy: const.relation,
                                        toItem: nil,
                                        attribute: const.attribute,
                                        multiplier: const.multiplier,
                                        constant: const.constant)
    constraint.identifier = const.identifier

    NSLayoutConstraint.activate([constraint])
    return constraint
}

func >>- <T:UIView> (lhs: (T,T),attributes: [NSLayoutAttribute]){
    for attribute in attributes{
        lhs >>- {
            $0.attribute = attribute
        }
    }
}

func >>- <T:UIView> (lhs: T, attributes: [NSLayoutAttribute]){
    for attribute in attributes{
        lhs >>- {
            $0.attribute = attribute
        }
    }
}

以下是其声明&#34;无法在当前上下文中推断闭包类型&#34;

1 个答案:

答案 0 :(得分:3)

我设法通过显式给出一个闭包函数所需的类型来解决这个问题。

    internetCheck()

    if reachability!.isReachable() {
        dispatch_async(dispatch_get_main_queue()) {
            let token: NSString!

            let   urlPath: NSURL!

            if provider .isEqualToString("No"){
                urlPath  = NSURL(string: kAPI_SERVERBASEURL + (url as String))
            }
            else{
                urlPath  = NSURL(string: kAPI_SERVERBASEURLSEARCHPROVIDER + (url as String))
            }
            print("URL Called sucess: \(url)")
            var postJsonData = NSData()
            var jsonString   = NSString()

            do {
                postJsonData = try NSJSONSerialization.dataWithJSONObject(dictRequest, options:[])
                jsonString = NSString(data: postJsonData, encoding: NSUTF8StringEncoding)!
                NSLog("request - %@", jsonString);

                // do other stuff on success

            } catch {
                print("JSON serialization failed:  \(error)")
            }

            let request = NSMutableURLRequest(URL: urlPath);
            request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
            request.HTTPShouldHandleCookies = false
            request.timeoutInterval = 120 ;
            request.HTTPMethod = "POST";

            if NSUserDefaults.standardUserDefaults().valueForKey(kAccessToken) != nil{

                token = NSUserDefaults.standardUserDefaults().valueForKey(kAccessToken) as! NSString
                //token = "tk_1vNoEoZRxJwY"
                //request.setValue("\(token)", forHTTPHeaderField: "access_token")
                request.setValue("\(token)", forHTTPHeaderField: "ACCESS-TOKEN")
            }

            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = postJsonData
            var task: NSURLSessionTask? = nil
            let session = NSURLSession.sharedSession()
            task = session.dataTaskWithRequest(request) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
                //  self.hideNetworkActivity()
                if((error) != nil) {
                    print(error!.localizedDescription)

                    let responseObj=ResponseObj()
                    if response==nil {

                    } else {
                        let responseStatus = response! as!  NSHTTPURLResponse
                        responseObj.responseCode = responseStatus.statusCode
                    }
                    responseObj.responseErrMessage = kAlertMessage_ServerNotWorking
                    self.delegate?.performSelector(self.callbackSelector!, withObject:responseObj)


                    return
                }else {
                    print("Succes:")
                    do {

                        let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
                        print("Value of JSON: \(jsonData)")

                        dispatch_async(dispatch_get_main_queue()) {
                            if jsonData.valueForKey("message") as! String == "Session expired."{
                                AppDelegate().appDelegate().hideHudViewSuccess()

                                let alert = UIAlertController(title: "", message:jsonData.valueForKey("message") as? String, preferredStyle: UIAlertControllerStyle.Alert)

                                alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { action in
                                    AppDelegate().appDelegate().logout()
                                }))
                                self.delegate!.presentViewController(alert, animated: true, completion: nil)
                            }
                            return
                        }

                        var responseObj=ResponseObj()
                        //Changes if response code is 605 it is Token not found in that case view will navigate to Home screen
                        responseObj = try! responseObj.objectFormat(jsonData)
                        self.delegate?.performSelector(self.callbackSelector!, withObject:responseObj)
                        dispatch_async(dispatch_get_main_queue()) {
                            AppDelegate().appDelegate().hideHudViewSuccess()
                        }
                        return

                    } catch {
                        print("JSON Error: \(error)")
                        let responseObj=ResponseObj()
                        responseObj.responseErrMessage = kAlertMessage_ServerNotWorking
                        self.delegate?.performSelector(self.callbackSelector!, withObject:responseObj)
                        return
                    }
                }
            }
            task!.resume()
        }
    }else{
        dispatch_async(dispatch_get_main_queue()) {
            print("URL Called failer: \(url)")

            let responseObj=ResponseObj()
            responseObj.responseErrMessage = kAlertMessage_InternetNotAvailable
            self.delegate?.performSelector(self.callbackSelector!, withObject:responseObj)
            return
    }

我不确定为什么要求我明确说明,但最终会有效。