【发布时间】:2017-03-20 20:08:12
【问题描述】:
我的代码中出现此错误:
Contextual type 'Void' (aka '()') cannot be used with array literal
我应该如何解决这个问题?谢谢!
我正在使用 MVC 模型。这是我的代码:
let users: [User] = {
let ref = FIRDatabase.database().reference().child("position")
ref.observeSingleEvent(of: .childAdded, with: { (snapshot) in
if let locationDict = snapshot.value as? [String: AnyObject] {
guard let lat = locationDict["latitude"] as? CLLocationDegrees,
let long = locationDict["longitude"] as? CLLocationDegrees else { return }
let position = CLLocationCoordinate2D(latitude: lat, longitude: long)
let userPosition = User(name: "Name", position: position)
return [userPosition] //Here is my error
}
})
}()
override func cellClasses() -> [DatasourceCell.Type] {
return [UserCell.self]
}
override func item(_ indexPath: IndexPath) -> Any? {
return users[indexPath.item]
}
override func numberOfItems(_ section: Int) -> Int {
return users.count
}
}
我的用户属性:
import Foundation
import MapKit
struct User {
let name: String
let position: CLLocationCoordinate2D
}
还有我的细胞:
import LBTAComponents
import MapKit
import CoreLocation
class UserCell: DatasourceCell, CLLocationManagerDelegate, MKMapViewDelegate {
let distanceSpan: Double = 500
override var datasourceItem: Any? {
didSet {
guard let user = datasourceItem as? User else { return }
nameLabel.text = user.name
MapView.setCenter(user.position, animated: false)
MapView.region = MKCoordinateRegion(center: user.position, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
let locationPin = user.position
let annotation = MKPointAnnotation()
annotation.coordinate = locationPin
MapView.addAnnotation(annotation)
MapView.showAnnotations([annotation], animated: true)
}
}
【问题讨论】:
-
闭包内部的 return 语句从闭包返回,而不是从外部函数返回。闭包有一个
Void返回值,所以你不能在里面返回一个数组。 -
好吧,我对 Swift 有点陌生...你知道我该如何解决这个问题吗?或者以另一种方式来做?谢谢!
-
你能从你的项目中发布一些额外的代码,展示你如何使用
users属性吗?这对于确定您当前的设计需要如何更改以正确利用数据库调用的异步回调非常重要。 -
所以,如果您需要更多,请告诉我!
标签: ios swift firebase swift3 firebase-realtime-database