昨天我已将IOS Swift项目切换到新的XCode 6.3和Swift 1.2。到目前为止,我已经完成了很好的构建,但是有一次应用程序崩溃了错误消息"致命错误:数组元素无法桥接到Objective-C"在一行看起来像这样:
let services = services as! [ServiceObject]
我已经读过错误是因为我将Objective C对象作为Swift数组中的成员,现在不再自动桥接到NSArray,所以我必须要么使用ServiceObject类型的对象非Obj-C或者宣布"服务"作为NSArray。奇怪的是ServiceObject不是Objective-C对象。这是该类的声明:
class ServiceObject: MonitoringObject {
let serviceDescription: String
let host: HostObject
var duration = 0
var plugin_output = ""
var active_checks_enabled = 0
var display_name = ""
var has_been_checked = 0
var acknowledged = 0
var acknowledgement_type = 0
var scheduled_downtime_depth = 0
var is_flapping = 0
var state = ServiceState.OK
var name: String {
return serviceDescription
}
init(serviceDescription: String, host: HostObject) {
self.host = host
self.serviceDescription = serviceDescription
}
var durationText: String {
if duration == -1 || duration == 0{
return "N/A"
} else if duration > 86400 {
let days = Int(floor(Float(duration) / 86400))
let hours = Int(floor(Float(duration % 86400) / 3600))
return "\(days)d, \(hours)h"
} else if duration > 3600 {
let hours = Int(floor(Float(duration) / 3600))
let minutes = Int(floor(Float(duration) % 3600 / 60))
return "\(hours)h, \(minutes)m"
} else if duration > 60 {
let minutes = Int(floor(Float(duration) / 60))
let seconds = duration % 60
return "\(minutes)m, \(seconds)s"
} else {
return "\(duration)s"
}
}
}
此外,协议" MonitoringObject" ServiceObject符合的不是Obj-C:
protocol MonitoringObject {
var name: String { get }
}
有没有人知道错误和崩溃的来源?
编辑:这是包含失败行的整个方法,以使上下文更清晰:
private func buildHostServicesIndex(services: [MonitoringObject]) -> [HostServicesEntry] {
//typealias HostServicesEntry = (HostObject, [ServiceObject])
let services = services as! [ServiceObject]
let hosts = services.map {
(service) -> HostObject in
service.host
}
let distinctHosts = Helpers.distinct(hosts)
return distinctHosts.map {
(host) -> HostServicesEntry in
return (host, services.filter {
(service) -> Bool in
service.host == host
})
}
}