【问题标题】:Cannot convert value of type - Swift无法转换类型的值 - Swift
【发布时间】:2016-03-05 20:01:30
【问题描述】:

我正在尝试通过迁移现有的 Objective-C 项目来学习 Swift,但其中一种方法存在一些问题。

我收到以下错误:“无法将类型 '(SBStop, UInt, _) -> Void' 的值转换为预期的参数类型 '(AnyObject, Int, UnsafeMutablePointer) -> Void'”

关于如何让这个工作的任何建议?

斯威夫特:

stops.enumerateObjectsUsingBlock({(stopItem: SBStop, idx: UInt, stop) -> Void in
            stopLocation = CLLocation(latitude: stopItem.latitude, longitude: stopItem.longitude)
            stopItem.distance = stopLocation.distanceFromLocation(location)
        })

工作 Objective-C 代码:

    [stops enumerateObjectsUsingBlock:^(SBStop *stopItem, NSUInteger idx, BOOL *stop) {
        stopLocation = [[CLLocation alloc] initWithLatitude:stopItem.latitude longitude:stopItem.longitude];
        stopItem.distance = [stopLocation distanceFromLocation:location];         // in meters
    }];

【问题讨论】:

    标签: ios objective-c swift


    【解决方案1】:

    看起来您在完成闭包中使用了不正确的类型注释。应该这样做:

       stops.enumerateObjectsUsingBlock({(stopItem, _ , _) in
                   guard let stopItem = stopItem as? SBStop else { return }
                   stopLocation = CLLocation(latitude: stopItem.latitude, longitude: stopItem.longitude)
                   stopItem.distance = stopLocation.distanceFromLocation(location)
               })
    

    说明: 您使用的库将完成块的参数定义为(AnyObject, Int, UnsafeMutablePointer)。如果您希望 AnyObject 属于特定类型,则需要适当地转换它(在本例中使用 guard let)

    _ 是一个 Swift 主义,表示未使用的参数。

    除非另有说明,否则-> Void 隐含在闭包中,因此这里没有明确需要。

    【讨论】:

    • 完美,路德!这解决了我的问题!并感谢您的解释,我真的很感激!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    相关资源
    最近更新 更多