gpt4 book ai didi

ios - 上下文类型 'Void' (又名 '()' )不能与数组文字一起使用

转载 作者:行者123 更新时间:2023-11-30 12:35:34 24 4
gpt4 key购买 nike

我的代码中出现此错误:

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)

}

}

最佳答案

您正在为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]
}
})
}
}

关于ios - 上下文类型 'Void' (又名 '()' )不能与数组文字一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42912999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com