NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

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!

   

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

   

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

   

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

   

Hacking with Swift is sponsored by Paw

SPONSORED Use Paw to build, test and describe web APIs. Paw has a lightning fast native macOS interface to compose requests, collaborate in real-time on API specs, and generate client code for your applications. You can import and export API definitions.

Discover Paw for Mac

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

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.