【问题标题】:Swift 3 - Invalid conversion from throwing function typeSwift 3 - 抛出函数类型的无效转换
【发布时间】:2016-10-04 13:08:52
【问题描述】:

我是 swift 新手,
我不明白为什么即使在进行 do catch 治疗时也会出现此错误。

我正在阅读类似的问题,但到目前为止还没有他们中的人解决了这个错误:
Invalid conversion from throwing function type '(_) throws -> (). to non-throwing function type '([BeaconModel]) -> ()'BeaconModel.fetchBeaconsFromRestApi(completionHandler: { .....

有错误的代码:

do{

    let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    let db = try Connection("\(path)/db.sqlite3")

    let beaconsTbl = Table("beacons")
    let id = Expression<Int64>("id")
    let uuid = Expression<String>("uuid")
    let major = Expression<String>("major")
    let minor = Expression<String>("minor")

    try db.run(beaconsTbl.create { t in
        t.column(id, primaryKey: true)
        t.column(uuid)
        t.column(major)
        t.column(minor)
    })

    BeaconModel.fetchBeaconsFromRestApi(completionHandler: {
        beacons in
        for item in beacons{

            let insert = beaconsTbl.insert(id <- item.id!, uuid <- item.uuid!, major <- item.major!, minor <- item.minor!)
            try db.run(insert)
        }
    })

} catch {
    print("Error creating the database")
}

获取方法:

static func fetchBeaconsFromRestApi( completionHandler: @escaping (_ beacons: [BeaconModel]) -> ()){

    Alamofire.request(Constants.Beacons.URLS.ListAllbeacons).responseArray(keyPath: "data") { (response: DataResponse<[BeaconModel]>) in

        let beaconsArray = response.result.value
        if let beaconsArray = beaconsArray {
            completionHandler(beaconsArray)
        }
    }
}

它使用AlamofireAlamofireObjectMapper。你能看到我错过了什么吗?

感谢您的帮助

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    fetchBeaconsFromRestApi 中的completionHandler 不应抛出。所以你应该用do - catch包装所有的抛出调用:

    BeaconModel.fetchBeaconsFromRestApi(completionHandler: {
        beacons in
        for item in beacons{
    
            let insert = beaconsTbl.insert(id <- item.id!, uuid <- item.uuid!, major <- item.major!, minor <- item.minor!
            do {
                try db.run(insert)
            } catch {
                print("Error creating the database")
            }
        }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多