Json Swift 3:扩展不能包含存储的属性
我试图测试Apple Swift 3文档()中的一些代码,但我得到两个错误,即“扩展可能不包含存储属性” 代码如下:Json Swift 3:扩展不能包含存储的属性,json,properties,swift3,httprequest,Json,Properties,Swift3,Httprequest,我试图测试Apple Swift 3文档()中的一些代码,但我得到两个错误,即“扩展可能不包含存储属性” 代码如下: import Foundation struct Restaurant { enum Meal: String { case breakfast, lunch, dinner } let name: String let location: (latitude: Double, longitude: Double) let meals: Set<Meal>
import Foundation
struct Restaurant {
enum Meal: String {
case breakfast, lunch, dinner
}
let name: String
let location: (latitude: Double, longitude: Double)
let meals: Set<Meal>
}
extension Restaurant {
private let urlComponents: URLComponents // base URL components of the web service
private let session: URLSession // shared session for interacting with the web service
static func restaurants(matching query: String, completion: @escaping ([Restaurant]) -> Void) {
var searchURLComponents = urlComponents
searchURLComponents.path = "/search"
searchURLComponents.queryItems = [URLQueryItem(name: "q", value: query)]
let searchURL = searchURLComponents.url!
session.dataTask(url: searchURL, completion: { (_, _, data, _)
var restaurants: [Restaurant] = []
if let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
for case let result in json["results"] {
if let restaurant = Restaurant(json: result) {
restaurants.append(restaurant)
}
}
}
completion(restaurants)
}).resume()
}
}
<代码>导入基础
结构餐厅{
枚举:字符串{
凯斯早餐、午餐、晚餐
}
let name:String
let位置:(纬度:双精度,经度:双精度)
套餐:套餐
}
扩展餐厅{
private let urlComponents:urlComponents//web服务的基本URL组件
私有let会话:URLSession//用于与web服务交互的共享会话
静态func餐厅(匹配查询:字符串,完成:@escaping([Restaurant])->Void){
var searchURLComponents=urlComponents
searchURLComponents.path=“/search”
searchURLComponents.queryItems=[URLQueryItem(名称:“q”,值:query)]
让searchURL=searchURLComponents.url!
dataTask(url:searchURL,完成:{({,},数据,})
var餐厅:[餐厅]=[]
如果let data=data,
让json=try?JSONSerialization.jsonObject(with:data,options:[])作为?[String:Any]{
对于case let,结果为json[“results”]{
如果let restaurant=restaurant(json:result){
餐厅。附加(餐厅)
}
}
}
完工(餐厅)
})1.简历()
}
}
我在urlComponents行和session行中得到错误。您不能在扩展中使用存储的属性。但是您可以使用像这里这样的计算getter和setter-。顺便问一下,为什么在餐厅扩展中使用URL组件和会话??最好将其移动到另一个服务层。您不能在扩展中使用存储的属性。但是您可以使用像这里这样的计算getter和setter-。顺便问一下,为什么在餐厅扩展中使用URL组件和会话??最好将其移动到另一个服务层。