NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Cannot find 'data' in scope error.

Forums > SwiftUI

Hello, I'm new to Swift and ran into an error that has confused me. I have the latest versions of Xcode on my Mac and Swift Playgrounds on my iPad. I have tried this on both with the same error.

Here is the code in question. It from this site and the same code Paul uses in the tutorial YouTube video. Here is the link to the tutorial: https://www.hackingwithswift.com/books/ios-swiftui/sending-and-receiving-codable-data-with-urlsession-and-swiftui

import SwiftUI

struct Response: Codable {
    var results: [Result]
}

struct Result: Codable {
    var trackId: Int
    var trackName: String
    var collectionName: String
}

struct ContentView: View {
    @State private var results = [Result]()

    var body: some View {
        List(results, id: \.trackId) { item in
            VStack(alignment: .leading) {
                Text(item.trackName)
                    .font(.headline)
                Text(item.collectionName)
            }
        }
        .task {
            await loadData()
        }
    }

    func loadData() async {

        guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else {
            print("Invalid URL")
            return
        }

        do {
            let (data, _) = try await URLSession.shared.data(from: url)
        } 
        catch {
            print("Invalid data")
        }

        if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {   // <-- Error here.  Cannot find 'data' in scope.
            results = decodedResponse.results
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Isn't 'data' defined with the let (data, _)

I think I must be missing something, any help would be greatly appreceated.

James

1      

You have defined data within a do {} catch {} block:

do {
    let (data, _) = try await URLSession.shared.data(from: url)
} 
catch {
    print("Invalid data")
}

so data is only in scope within that do {} catch {} block.

You should move your decoding line inside the do {} part. That's why Paul has the // more code to come part there. The decoding bit is the "more code".

2      

Thank you. Works like the tutorial now. I'll do some reading on scopes and the do / catch.

James

1      

I'm hoping something has changed since this answer was posted. I'm having exactly the same error that James was above, but I have located the decoding line inside the do {}. I've compared my code with the article, and also rewatched the video many times, but I can't see what might be wrong. I am using Xcode 14.0.1 and Swift 5.7. Her is a snippet of my code:

func loadData() async { guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else { print("Invalid URL") return }

do {
    let (data, _) = try await URLSession.shared.data(from: url)

    if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
        results = decodedResponse.results
    }
} catch {
    print("Invalid data")
}

}

Here's hoping you can help me!

   

I'm hoping something has changed since this answer was posted. I'm having exactly the same error that James was above, but I have located the decoding line inside the do {}. I've compared my code with the article, and also rewatched the video many times, but I can't see what might be wrong. I am using Xcode 14.0.1 and Swift 5.7. Her is a snippet of my code:

func loadData() async { guard let url = URL(string: "https://itunes.apple.com/search?term=taylor+swift&entity=song") else { print("Invalid URL") return }

do {
    let (data, _) = try await URLSession.shared.data(from: url)

    if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
        results = decodedResponse.results
    }
} catch {
    print("Invalid data")
}

}

Here's hoping you can help me!

   

Please ignore the request and <whine> above. I printed out my program and through careful scanning of the text, I discovered an extraneous and misplaced bracket. After realigning, the code works perfectly. thanks in advance for all the contributors who post to this forum. I really wish that Paul would provide a completed code snippet for each of the project videos. I spend a lot of wasted time tracking down these errors (largely to my inexperience. Is there an app or extension which can spot things like this?

   

@geoff  

Unbalanced brackets are frustrating for sure. The errors are not always informative, or there may be a single root-cause error drowning in a sea of irrelevant ones. Perhaps not what you want to hear, but I consider it a fundamental skill to be able to read and recognize errors.

For fun, I added an extra bracket to a random spot in the Moonshot code just to see what would happen:

/Users/geoff/Documents/Swift/Moonshot/Moonshot/ContentView.swift:19:24: error build: Type '() -> VStack<some View>' cannot conform to 'View'

/Users/geoff/Documents/Swift/Moonshot/Moonshot/ContentView.swift:52:17: error build: Type '() -> VStack<some View>' cannot conform to 'View'

/Users/geoff/Documents/Swift/Moonshot/Moonshot/ContentView.swift:52:24: error build: Type '() -> VStack<some View>' cannot conform to 'View'

/Users/geoff/Documents/Swift/Moonshot/Moonshot/ContentView.swift:69:14: error build: Cannot infer contextual base in reference to member 'navigationTitle'

/Users/geoff/Documents/Swift/Moonshot/Moonshot/ContentView.swift:70:26: error build: Cannot infer contextual base in reference to member 'darkBackground'

/Users/geoff/Documents/Swift/Moonshot/Moonshot/ContentView.swift:71:36: error build: Cannot infer contextual base in reference to member 'dark'

/Users/geoff/Documents/Swift/Moonshot/Moonshot/ContentView.swift:85:1: error build: Expected '}' in struct

As you can see there are 7 errors because of the misplaced brace and only the last one gives a clue that the problem is because of the brace. However, it's good to be familiar with the other errors. Now I know that "Type ... cannot conform to 'View'" is sometimes seen because of bracket typo. I would simply file it under the learnings you gain when typing code in by hand. And I also know to scan the whole list looking for a simple culprit even if it's the very last one.

It was fun to see how much the Swift compiler would barf over a single character. :) Sometimes it's educational just to indulge your curiosity for a bit. On that note, I tend to do command-B a lot just to make sure I haven't made any silly typos. I don't think anybody codes as fast as Paul does in his videos because you have to stop a lot to think. Perfect time to do command-B and make sure things are still compiling all right.

Also, Paul has uploaded the canonical versions of each project here, which is helpful sometimes in comparing problematic code. I'm not sure whether he uploaded the "technique" portions of each project though, which I think is what you are asking for.

   

There are couple of methods to keep in mind.

Double-clicking on a brace, bracket, square bracket or quotes will highlight the extent in the code of that delimiter. Also using Ctrl + I over selected lines of code will re-indent the code as necessary.

Both methods could help identify missing or extraneous delimiters (brackets, braces, …).

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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

You are not logged in

Log in or create account
 

Link copied to your pasteboard.