UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: Pro Swift Course - filter error

Forums > Swift

Hi I'm doing my first course through the site Pro Swift, it's been amazing.

I'm up to the filter video and I've copied the code exactly but I'm getting an error with this

let scores = ["Paul": 100, "Taylor": 95, "Adele": 90, "Michael": 865, "Justin": 60]
let goodScores = scores.filter { $1 > 85 }
print(goodScores[0].0)  
print(goodScores[0].1)  <- Error here - Cannot convert value of type 'Int' to expected arg type 'Dictionary<String, Int>

Cannot convert value of type 'Int' to expected argument type 'Dictionary<String, Int>.Index'

I'm running swift 5.2, and the course is in swift 5. Can I not access a Dictionary value with an integer as the index?

Thanks!

2      

Dictionaries aren't index based, but are key-value types. You can do something like this:

let scores = ["Paul": 100, "Taylor": 95, "Adele": 90, "Michael": 865, "Justin": 60]
let goodScores = scores.filter { $1 > 85 }
goodScores.forEach { (key, value) in
    print("\(key) scored \(value)")
}

Will print ...

Paul scored 100
Michael scored 865
Adele scored 90
Taylor scored 95

2      

Great thanks, I thought that was the case, but I'm not sure why it compiling for Paul in the video?

2      

but I'm not sure why it compiling for Paul in the video?

Because since Paul recorded that video, the behavior of filtering dictionaries changed so that filter returns a Dictionary rather than a tuple. See item #4 here: Five useful methods of dictionaries

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.