【问题标题】:Swift how can I make dictionary array?Swift 如何制作字典数组?
【发布时间】:2014-12-14 03:15:51
【问题描述】:

object-C 风格

@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

我想在 Swift 中编写相同的代码

所以我输入了如下的swift样式

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 错误

不知道为什么会报错

你能帮帮我吗?

【问题讨论】:

    标签: arrays dictionary collections swift


    【解决方案1】:

    swift中的数组不带参数,只需将数组设置为[](有或无值)即可创建一个,例如:

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

    将创建一个整数数组。

    另外,swift中的字典需要知道key和value的类型,例如:

    Dictionary<String, String>
    

    但也有一种创建字典的简写方式,如下所示:

    [String:String]
    

    (假设 String 是您的键和值的类型)。

    因此,对于您的示例,您可以重写 datalist 对象以声明为:

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

    然后您可以按照您使用它的方式使用 datalist 对象,或者将[String:String] 对象附加到它。

    【讨论】:

      猜你喜欢
      • 2015-08-05
      • 2016-11-08
      • 1970-01-01
      • 1970-01-01
      • 2015-05-10
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多