Module 5 Couldn't Parse jsonData

Shows error_instance = (Builtin.RawPointer) 0x0 when parsing the jsonData in Module 5. Been debugging for days…

Replace

print("Couldn't parse local data")

with

print(error)

and see what you get. That should be much more informative.

If it still isn’t doing what you want it to do, please post some more code showing what you are doing to trigger an error.

can you show your code to parse the json? also make sure that the JSON matches EXACTLY with your class so you won’t encounter a mismatch

Oh, and when you post code, please post it as text, not a screenshot. You can do this by placing three backticks ``` on the line before your code and three backticks ``` on the line after your code so that it will be formatted properly. You can also highlight an entire code block and click the </> button on the toolbar to wrap the block for you.

This makes it far easier to read and also makes it easier for other posters to copy/paste the code in order to test solutions and such.

Hi,
I found this error while parsing json. The error is generated using print(error).
typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: “Index 0”, intValue: 0), CodingKeys(stringValue: “content”, intValue: nil)], debugDescription: “Expected to decode Array but found a dictionary instead.”, underlyingError: nil))

Well, we can’t tell you exactly what’s wrong without seeing the JSON you are trying to parse and the code you are using to parse it.

But generally, that error means Codable is expecting something like this:

[
    ...
]

and you gave it something like this:

{
    ...
}

Post some code and someone will be able to help you.

1 Like

I think the json data in M5L3 resources, brackets are missing in content and test arrays. On adding these brackets, I’m able to parse JSON data.

[
{
“id”: 0,
“category”: “Swift”,
“content”: {
“id”: 0,
“image”: “swift”,
“time”: “3 hours”,
“description”: “Understand the fundamentals of the Swift programming language.”,
“lessons”: [
{
“id”: 0,
“title”: “Constants and Variables”,
“video”: “Learn%20Swift%20for%20Beginners%20Lesson%201%20-%20Variables%20(Swift%205%20compatible)-2OZ07fklur8.mp4”,
“duration”: “17 minutes”,
“explanation”: “

Constants and variables must be declared before they’re used. You declare constants with the let keyword and variables with the var keyword. Here’s an example of how constants and variables can be used to track the number of login attempts a user has made:

  1. let maximumNumberOfLoginAttempts = 10
  2. var currentLoginAttempt = 0

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.

  1. var welcomeMessage: String

Constant and variable names can contain almost any character, including Unicode characters. Constant and variable names can’t contain whitespace characters, mathematical symbols, arrows, private-use Unicode scalar values, or line- and box-drawing characters. Nor can they begin with a number, although numbers may be included elsewhere within the name. Once you’ve declared a constant or variable of a certain type, you can’t declare it again with the same name, or change it to store values of a different type. Nor can you change a constant into a variable or a variable into a constant.


},
{
“id”: 1,
“title”: “Numbers”,
“video”: “Learn%20Swift%20for%20Beginners%20Lesson%201%20-%20Variables%20(Swift%205%20compatible)-2OZ07fklur8.mp4”,
“duration”: “17 minutes”,
“explanation”: “

Integers are whole numbers with no fractional component, such as 42 and -23. Integers are either signed (positive, zero, or negative) or unsigned (positive or zero). Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C, in that an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer is of type Int32. Like all types in Swift, these integer types have capitalized names. In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform’s native word size:

<ul class=“simple”>
  • On a 32-bit platform, <code class=“docutils literal notranslate”><span class=“pre”>Int is the same size as <code class=“docutils literal notranslate”><span class=“pre”>Int32.
  • On a 64-bit platform, <code class=“docutils literal notranslate”><span class=“pre”>Int is the same size as <code class=“docutils literal notranslate”><span class=“pre”>Int64.
  • Unless you need to work with a specific size of integer, always use Int for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, Int can store any value between -2,147,483,648 and 2,147,483,647, and is large enough for many integer ranges.

    Floating-point numbers are numbers with a fractional component, such as 3.14159, 0.1, and -273.15. Floating-point types can represent a much wider range of values than integer types, and can store numbers that are much larger or smaller than can be stored in an Int. Swift provides two signed floating-point number types:

    <ul class=“simple”>
  • <code class=“docutils literal notranslate”><span class=“pre”>Double represents a 64-bit floating-point number.
  • <code class=“docutils literal notranslate”><span class=“pre”>Float represents a 32-bit floating-point number.

  • },
    {
    “id”: 2,
    “title”: “Booleans”,
    “video”: “Learn%20Swift%20for%20Beginners%20Lesson%201%20-%20Variables%20(Swift%205%20compatible)-2OZ07fklur8.mp4”,
    “duration”: “17 minutes”,
    “explanation”: “

    Swift has a basic Boolean type, called Bool. Boolean values are referred to as logical, because they can only ever be true or false. Swift provides two Boolean constant values, true and false:

    1. let orangesAreOrange = true
    2. let turnipsAreDelicious = false

    The types of orangesAreOrange and turnipsAreDelicious have been inferred as Bool from the fact that they were initialized with Boolean literal values. As with Int and Double above, you don’t need to declare constants or variables as Bool if you set them to true or false as soon as you create them. Type inference helps make Swift code more concise and readable when it initializes constants or variables with other values whose type is already known.

    Boolean values are particularly useful when you work with conditional statements such as the if statement:

    1. if turnipsAreDelicious {
    2. print(‘Mmm, tasty turnips!’)
    3. } else {
    4. print(‘Eww, turnips are horrible.’)
    5. }
    6. // Prints ‘Eww, turnips are horrible.’

    },
    {
    “id”: 3,
    “title”: “Optionals”,
    “video”: “Learn%20Swift%20for%20Beginners%20-%20Ep%2013%20-%20Optionals-uT2IHQpE3ms.mp4”,
    “duration”: “17 minutes”,
    “explanation”: “

    You use optionals in situations where a value may be absent. An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.

    Here’s an example of how optionals can be used to cope with the absence of a value. Swift’s Int type has an initializer which tries to convert a String value into an Int value. However, not every string can be converted into an integer. The string “123” can be converted into the numeric value 123, but the string ‘hello, world’ doesn’t have an obvious numeric value to convert to.

    The example below uses the initializer to try to convert a String into an Int:

    1. let possibleNumber = “123"
    2. let convertedNumber = Int(possibleNumber)
    3. // convertedNumber is inferred to be of type ‘Int?’, or ‘optional Int’

    Because the initializer might fail, it returns an optional Int, rather than an Int. An optional Int is written as Int?, not Int. The question mark indicates that the value it contains is optional, meaning that it might contain some Int value, or it might contain no value at all. (It can’t contain anything else, such as a Bool value or a String value. It’s either an Int, or it’s nothing at all.)

    You can use an if statement to find out whether an optional contains a value by comparing the optional against nil. You perform this comparison with the “equal to” operator (==) or the “not equal to” operator (!=).

    <div class=“highlight-swift notranslate”><div class=“code-sample”><div class=“Swift highlight”><ol class=“code-lines”>
  • <span class=“k”>if <span class=“nv”>convertedNumber != <span class=“k”>nil {
  • <span class=“nv”>print(<span class=“s”>“convertedNumber contains some integer value.”)
  • }
  • <span class=“c”>// Prints “convertedNumber contains some integer value.”

  • },
    {
    “id”: 4,
    “title”: “Operators”,
    “video”: “Learn%20Swift%20for%20Beginners%20Lesson%201%20-%20Variables%20(Swift%205%20compatible)-2OZ07fklur8.mp4”,
    “duration”: “17 minutes”,
    “explanation”: “

    An operator is a special symbol or phrase that you use to check, change, or combine values. For example, the addition operator (+) adds two numbers, as in “let i = 1 + 2”.

    The assignment operator (a = b) initializes or updates the value of a with the value of b:

    1. let b = 10
    2. var a = 5
    3. a = b
    4. // a is now equal to 10

    Swift supports the four standard arithmetic operators for all number types:

    • Addition (+)
    • Subtraction (-)
    • Multiplication (*)
    • Division (/)
    1. 1 + 2 // equals 3
    2. 5 - 3 // equals 2
    3. 2 * 3 // equals 6
    4. 10.0 / 2.5 // equals 4.0

    Swift supports the following comparison operators:

    • Equal to (a == b)
    • Not equal to (a != b)
    • Greater than (a > b)
    • Less than (a < b)
    • Greater than or equal to (a >= b)
    • Less than or equal to (a <= b)

    Each of the comparison operators returns a Bool value to indicate whether or not the statement is true:

    1. 1 == 1 // true because 1 is equal to 1
    2. 2 != 1 // true because 2 is not equal to 1
    3. 2 > 1 // true because 2 is greater than 1
    4. 1 < 2 // true because 1 is less than 2
    5. 1 >= 1 // true because 1 is greater than or equal to 1
    6. 2 <= 1 // false because 2 is not less than or equal to 1

    },
    {
    “id”: 5,
    “title”: “Strings”,
    “video”: “Learn%20Swift%20for%20Beginners%20Lesson%201%20-%20Variables%20(Swift%205%20compatible)-2OZ07fklur8.mp4”,
    “duration”: “17 minutes”,
    “explanation”: “

    A string is a series of characters, such as ‘hello, world’ or ‘albatross’. Swift strings are represented by the String type. You can include predefined String values within your code as string literals. A string literal is a sequence of characters surrounded by double quotation marks (”). Use a string literal as an initial value for a constant or variable:

    1. let someString = “Some string literal value”

    },
    {
    “id”: 6,
    “title”: “Control Flow”,
    “video”: “Learn%20Swift%20for%20Beginners%20-%20Ep%205%20-%20Loops%20Part%201-vxyrLbmm9Oo.mp4”,
    “duration”: “17 minutes”,
    “explanation”: “

    Swift provides a variety of control flow statements. These include while loops to perform a task multiple times; if, guard, and switch statements to execute different branches of code based on certain conditions; and statements such as break and continue to transfer the flow of execution to another point in your code.

    You use the for-in loop to iterate over a sequence, such as items in an array, ranges of numbers, or characters in a string.

    1. let names = [“Anna”, “Alex”, “Brian”, “Jack”]
    2. for name in names {
    3. print(‘Hello, \(name)!’)
    4. }
    5. // Hello, Anna!
    6. // Hello, Alex!
    7. // Hello, Brian!
    8. // Hello, Jack!

    },
    {
    “id”: 7,
    “title”: “Functions”,
    “video”: “Learn%20Swift%20for%20Beginners%20-%20Ep%207%20-%20Functions%20Part%201-2kwyQ5w00Uc.mp4”,
    “duration”: “17 minutes”,
    “explanation”: "

    Functions are self-contained chunks of code that perform a specific task. You give a function a name that identifies what it does, and this name is used to “call” the function to perform its task when needed.

    When you define a function, you can optionally define one or more named, typed values that the function takes as input, known as parameters. You can also optionally define a type of value that the function will pass back as output when it is done, known as its return type.

    Every function has a function name, which describes the task that the function performs. To use a function, you “call” that function with its name and pass it input values (known as arguments) that match the types of the function’s parameters. A function’s arguments must always be provided in the same order as the function’s parameter list.

    The function in the example below is called greet(person:), because that’s what it does—it takes a person’s name as input and returns a greeting for that person. To accomplish this, you define one input parameter - a String value called person - and a return type of String, which will contain a greeting for that person:

    1. func greet(person: String) → String {
    2. let greeting = “Hello, " + person + “!”
    3. return greeting
    4. }

    All of this information is rolled up into the function’s definition, which is prefixed with the func keyword. You indicate the function’s return type with the return arrow → (a hyphen followed by a right angle bracket), which is followed by the name of the type to return.


    },
    {
    “id”: 8,
    “title”: “Structures and Classes”,
    “video”: “Learn%20Swift%20for%20Beginners%20-%20Ep%209%20-%20Classes%20Part%201-ZDzdz52tex4.mp4”,
    “duration”: “17 minutes”,
    “explanation”: “

    Structures and classes are general-purpose, flexible constructs that become the building blocks of your program’s code. You define properties and methods to add functionality to your structures and classes using the same syntax you use to define constants, variables, and functions. Structures and classes in Swift have many things in common. Both can:

    • Define properties to store values
    • Define methods to provide functionality
    • Define subscripts to provide access to their values using subscript syntax
    • Define initializers to set up their initial state
    • Be extended to expand their functionality beyond a default implementation
    • Conform to protocols to provide standard functionality of a certain kind

    Classes have additional capabilities that structures don’t have:

    <ul class=“simple”>
  • Inheritance enables one class to inherit the characteristics of another.
  • Type casting enables you to check and interpret the type of a class instance at runtime.
  • Deinitializers enable an instance of a class to free up any resources it has assigned.
  • Reference counting allows more than one reference to a class instance.
  • Structures and classes have a similar definition syntax. You introduce structures with the struct keyword and classes with the class keyword. Both place their entire definition within a pair of braces. Here’s an example of a structure definition and a class definition:

    1. struct Resolution {
    2. var width = 0
    3. var height = 0
    4. }
    5. class VideoMode {
    6. var resolution = Resolution()
    7. var interlaced = false
    8. var frameRate = 0.0
    9. var name: String?
    10. }

    },
    {
    “id”: 9,
    “title”: “Error Handling”,
    “video”: “Try%20_%20Catch%20Basics%20-%20Swift%20Error%20Handling%20-%20Xcode%2010,%20Swift%204-9hb80LAwf5c.mp4”,
    “duration”: “17 minutes”,
    “explanation”: “

    Error handling is the process of responding to and recovering from error conditions in your program. Swift provides first-class support for throwing, catching, propagating, and manipulating recoverable errors at runtime.

    Throwing an error lets you indicate that something unexpected happened and the normal flow of execution can’t continue. You use a throw statement to throw an error.

    When an error is thrown, some surrounding piece of code must be responsible for handling the error—for example, by correcting the problem, trying an alternative approach, or informing the user of the failure. You use a do-catch statement to handle errors by running a block of code. If an error is thrown by the code in the do clause, it is matched against the catch clauses to determine which one of them can handle the error.

    1. do {
    2. try expression
    3. statements
    4. } catch pattern 1 {
    5. statements
    6. } catch pattern 2 where condition {
    7. statements
    8. } catch pattern 3, pattern 4 where condition {
    9. statements
    10. } catch {
    11. statements
    12. }

    }
    ]
    },
    “test”: {
    “id”: 0,
    “image”: “testSwift”,
    “time”: “30 minutes”,
    “description”: “Gear up and put your Swift knowledge to the test.”,
    “questions”: [
    {
    “id”: 0,
    “content”: “

    What keyword is used to define a constant in Swift?

    ”,
    “correctIndex”: 2,
    “answers”: [
    “const”,
    “var”,
    “let”,
    “const var”
    ]
    },
    {
    “id”: 1,
    “content”: “

    How large is an Int?

    ”,
    “correctIndex”: 3,
    “answers”: [
    “16 bits”,
    “32 bits”,
    “64 bits”,
    “It depends on the platform”
    ]
    },
    {
    “id”: 2,
    “content”: “

    What is the value of b in the following expression?

    1. let a = false
    2. let b = false || ( true && !a )
    ”,
    “correctIndex”: 0,
    “answers”: [
    “true”,
    “false”
    ]
    },
    {
    “id”: 3,
    “content”: “

    What is the type and value of str in the following expression?

    1. let num = 12.0
    2. let str = String(num)
    ”,
    “correctIndex”: 1,
    “answers”: [
    "Type: String, Value: “12.0"”,
    "Type: String?, Value: “12.0"”,
    "Type: String, Value: “12"”,
    “Type: String?, Value: nil”
    ]
    },
    {
    “id”: 4,
    “content”: “

    What operator takes two numbers, and returns a boolean?

    ”,
    “correctIndex”: 4,
    “answers”: [
    “<”,
    “>”,
    “==”,
    “!=”,
    “all of the above”
    ]
    },
    {
    “id”: 5,
    “content”: “

    What does the following code output?

    1. let total = 0
    2. let nums = [0, 1, 2, 3]
    3. for num in nums {
    4. total += num
    5. }
    6. ”,
      “correctIndex”: 2,
      “answers”: [
      “0”,
      “3”,
      “6”,
      “10”
      ]
      },
      {
      “id”: 6,
      “content”: “

      What is the following function’s return type?

      1. func foo(bar: String, bizz: Bool) → Int {…}
      ”,
      “correctIndex”: 2,
      “answers”: [
      “String”,
      “Bool”,
      “Int”,
      “It doesn’t have a return type”
      ]
      },
      {
      “id”: 7,
      “content”: “Structures can’t:”,
      “correctIndex”: 3,
      “answers”: [
      “Define properties to store values”,
      “Define initializers to set up their initial state”,
      “Conform to protocols to provide standard functionality of a certain kind”,
      “Inherit the characteristics of another structure”
      ]
      },
      {
      “id”: 8,
      “content”: “Why might you throw an error?”,
      “correctIndex”: 1,
      “answers”: [
      “The code has become too complicated to continue writing”,
      “Something unexpected happened and the normal flow of execution can’t continue”,
      “To pass data to a caller method”
      ]
      },
      {
      “id”: 9,
      “content”: “How can you deal with an error?”,
      “correctIndex”: 3,
      “answers”: [
      “By correcting the problem”,
      “By trying an alternative approach”,
      “By informing the user of the failure”,
      “All of the above”
      ]
      }
      ]
      }
      }
      ]

    Above is the json file.
    I tried to put brackets in contents. Json data was then parsed. However, even while putting the code as mentioned in “M5L4: Building the home view”, I kept getting error in ForEach statement: “Cannot convert value of type ‘[Module]’ to expected argument type ‘Range’”
    I checked with the solution of M5L4. I found the error. It was in declaration of content.
    Now working fine.