2014-10-18 53 views
-1

对象的C风格的Swift如何制作字典数组?

@interface TestViewController:UIViewController{ 
    NSArray *dataList; 
} 
@end 

@implementation TestViewController 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSDictionary *dict1 =[[NSDictionary alloc] initWithObjectsAndKeys:@"32",@"age",@"andy",@"name", nil]; 
    NSDictionary *dict1 =[[NSDictionary alloc] initWithObjectsAndKeys:@"34",@"age",@"smith",@"name", nil]; 
    NSDictionary *dict1 =[[NSDictionary alloc] initWithObjectsAndKeys:@"27",@"age",@"jonathan",@"name", nil]; 

    dataList = [[NSArray alloc]initWithObjects:dict1,dict2,dict3,nil]; 
} 
@end 

我想让相同的代码在斯威夫特

所以我打字迅速风格如下

class ViewController: UIViewController { 
    var datalist = [Dictionary]() //Compile Error -> "Missing argument for parameter #1 in call" 
            // I can't understand error. What does it mean? 



    override func viewDidLoad() { 
     super.viewDidLoad() 
     let dict1 = ["age":"32","name":"andy"] 
     let dict2 = ["age":"34","name":"smith"] 
     let dict3 = ["age":"27","name":"jonathan"] 

     datalist = [dict1,dict2,dict3] //Compile Error -> 'ViewController' does not have a member named 'datalist' 
    } 
} 

但2错误

我不知道为什么发生错误

你能帮我吗?

回答

3

阵列中迅速不带参数,你只需通过设置阵列等于[](带或不带值),例如创建一个:

var array : [Int] = [] 
var array2 = [1,2,3] 

将创建一个整数数组。

而且,在迅速需要知道类型的键和值,例如字典:

Dictionary<String, String> 

但也有创造的字典,看起来像一个速记:

[String:String] 

(假设字符串是您的键和值的类型)。

因此,对于你的榜样,你可以重写你的DataList对象被声明为:

var datalist : [[String:String]] = [] 

然后你可以使用你正在使用它,或者通过附加[String:String]对象的方式在DataList对象。

+0

真的很感谢你 – user1272854 2014-10-19 04:32:14