Search code examples
swiftsyntax-error

What does Swift consider to be “multiple statements” that I haven’t separated?


I’m using swift playgrounds on iOS 15 and am confused about what the multiple statements are on this line:

let toSave = self.read(fromDocumentsWithFileName: "colors.txt") + "\n" + color.toHex(alpha: false) ?? "error saving")

I get the error “Consecutive statements on a line must be separated by ‘;’”

I tried changing around the expression onto its own variable and messing around with the “??” but no luck.


Solution

  • One thing to be aware of about the Swift compiler: Once it gets confused about your code, the error messages it gives may be pretty nonsensical.

    Rob explained this case very well in his comment, but you'll also get errors that seem downright wrong.

    When you get an error from the Swift compiler that doesn't make sense, ignore the letter of the error and just read it as "there is something wrong with my code. I have to figure it out myself."

    Edit:

    The first thing to do is to search for syntax errors in the code in question. In your case, you have an extra closing parenthesis, as others have pointed out. Try removing it. Then scan for any other errors. If you can't find any, simplify. Break your long compound statement into smaller pieces. If you have to create some local variables/constants, do it.

    (I tend to prefer short, simple statements anyway. They are easier to read and easier to debug. An optimizing compiler will usually optimize away things like temporary variables, so writing long, complex statements doesn't have much benefit.)