我的代码中出现此错误:
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)
}
}
答案 0 :(得分:0)
您正在为users
设置一个闭包,它被声明为类型[User]
(包含User
类型元素的数组。)
当你使用MVC时,我假设代码在UIViewController
内使用了这个(未经测试,但你明白了):
import CoreLocation
struct User {
var name:String
var position:CLLocationCoordinate
}
class MyViewController: UIViewController {
var ref = FIRDatabase.database().reference().child("position")
var users: [User]?
override func viewDidLoad() {
super.viewDidLoad()
setupRefObserver()
}
private func setupRefObserver() {
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)
users = [userPosition]
}
})
}
}