How to get the first 5 elements of an array in Swift?
Hi everyone! I'm writing a Swift app to display a list of latest news. I have an array that contains all the news received from the server. The array can be very large, but on the main screen I need to show only the first 5 elements.
Here's what my code looks like:
```swift
let allNews = ["News 1", "News 2", "News 3", "News 4", "News 5", "News 6", "News 7"]
var firstFiveNews: [String] = []
for i in 0..<5 {
if i < allNews.count {
firstFiveNews.append(allNews[i])
}
}
```
This works, but it seems very cumbersome and ugly to me. I'm a beginner in Swift, and I have a suspicion that there is a more elegant way to do this in the language.
I know that in other languages, for example in Python, you can simply write `all_ne
No answers yet.
Log in to leave an answer
Blogs