Richy Garrincha
Richy Garrincha

Reputation: 277

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

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. thanks

Upvotes: 1

Views: 1604

Answers (3)

linimin
linimin

Reputation: 6377

10 posts in a blog

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

Upvotes: 3

Dharmesh Kheni
Dharmesh Kheni

Reputation: 71854

Here is the another way to do that:

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

    blog.append(i)
}

Upvotes: 1

Mercurial
Mercurial

Reputation: 2165

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;

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

Upvotes: 0

Related Questions