-3

I have a Swift application.

I'm getting the error Expected expression after '?' in ternary expression from Xcode compiler

in

private func getContentPre(highlight: Highlight) -> String!

    {
        highlight.contentPre.count == 0 ? return ">" : return highlight.contentPre
    }

Apple docs says:

enter image description here

why isn't it possible to return in ternary expression like using if statement?

ozd
  • 1,194
  • 10
  • 34
  • return highlight.contentPre.count == 0 ? if true : if false – soulshined Dec 13 '19 at 16:17
  • Please read [documentation](https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html#ID71) – Aleksey Potapov Dec 13 '19 at 16:23
  • `return highlight.contentPre.count == 0 ? ">" : highlight.contentPre`, maybe...? or just write the evaluation out: `if highlight.contentPre.count == 0 { return ">" } else { return highlight.contentPre }` – holex Dec 13 '19 at 16:47

2 Answers2

3

You should re-write your function like this. This will evaluate the count of the contentPre variable and return the appropriate response.

private func getContentPre(highlight: Highlight) -> String! {
    return highlight.contentPre.count == 0 ? ">" :  highlight.contentPre
}

However as it would appear that contentPre would be a String you should use .isEmpty as it is more performant that checking the length of a String

private func getContentPre(highlight: Highlight) -> String! {
    return highlight.contentPre.isEmpty ? ">" :  highlight.contentPre
}
Andrew
  • 26,706
  • 9
  • 85
  • 101
-2

return does not return anything - I mean, to the function what calls it. Ternary operator's parameters must be expressions.

CoderCharmander
  • 1,862
  • 10
  • 18