-1
我遇到了swift問題。Swift中的嵌套類
我有city.swift文件2類是這樣的:
import Foundation
class Place {
var name : String!
var tel : String!
var kind : String!
}
class City {
var name : String!
var describe : String!
var hotel : Place!
init(data: NSDictionary)
{
self.name = data["name"] as? String
self.describe = data["city_description"] as? String
self.hotel = data["hotelName"] as? Place
}
}
我從JSON文件解析的信息。 我的問題是,當我試圖讓cities.hotel與此代碼:
if let items = json["cities"] as? NSArray {
for item in items {
let place = Place()
let cities = City(data: item as! NSDictionary)
println("\(cities.hotel)")
}
}
Xcode的還給我「無」,但city.name和city.describe做工精細。爲什麼? 感謝您的幫助。
編輯: 這是我的OBJ-C代碼和精細工作:
City.h
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *describe;
@property (nonatomic, retain) Place *hotel;
Place.h
@property (retain,nonatomic) NSString *name;
@property (retain,nonatomic) NSString *address;
@property (retain,nonatomic) NSString *tel;
collectionView.m
_jsonData = [NSJSONSerialization JSONObjectWithData:fileData options:kNilOptions error:&error];
_citiesListArray = [_jsonData objectForKey:@"cities"];
_citySingleList = [[NSMutableArray alloc] init];
for (NSDictionary *cityDictionary in _citiesListArray) {
City *city = [[City alloc] init];
city.name = [cityDictionary objectForKey:@"name"];
city.describe = [cityDictionary objectForKey:@"city_description"];
city.hotel = [cityDictionary objectForKey:@"hotels"];
NSLog(@"%@", city.hotel);
}
和JSON文件
"cities": [
{
"name": "City Name",
"city_description" : "City Describe",
"hotels": [
{
"name" : "Hotel Name",
"tel" : "Hotel Tel",
},
]
}
]
,當我的NSLog在city.hotel OBJ-C還給我
{
"name" : "Hotel Name",
"tel" : "Hotel Tel",
},
但我的銀行代碼回零,我哪裏出錯?再次感謝您的幫助
P.S酒店屬性是Place類的一個子類。因爲我想稍後使用它:
city.hotel.name = hotelDictionery["name"]
爲什麼強制展開屬性?而且你需要從JSON中解析出你的酒店。 – Abizern
@Abizern我編輯了答案。 – Beraliv
請不要濫用像這樣的隱式解包選項。不幸的是,對於Swift世界的其他人來說,除了你以外,最終可能會最終維護這些代碼。 – nhgrif