简体   繁体   English

如何快速创建由类实例填充的数组?

[英]how do I create an array populated by class instances in swift?

Hi all I am trying to create an array which is populated with some instances of my class BlogPost 大家好,我正在尝试创建一个数组,其中填充了我的类BlogPost的某些实例

I've started off with this :- 我从这里开始:-

{
var blog : [BlogPost] = []

for item in blog{
}

am I on the right track here? 我在正确的轨道上吗? just want to create 10 of these instances using a for loop any help appreciated. 只想使用for循环创建10个此类实例,不胜感激。 thanks 谢谢

博客中的10个帖子

var blog = (1...10).map { _ in BlogPost() }

Here is the another way to do that: 这是另一种方法:

var blog : [BlogPost] = []
for i in 1...10 {

    blog.append(i)
}
for item in blog{
}

won't do anything since your array is empty. 由于您的数组为空,因此不会执行任何操作。 Simply, iterate n(n being the number of posts you'd like to create) times, each time creating a new object and adding it to the array; 简单来说,重复n(n是您要创建的帖子数)次,每次创建一个新对象并将其添加到数组中;

let n : Int = 10
for(var i=0; i<n; i++){
    arr.append(BlogPost())
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM