Search code examples
iosswiftternary

Try to return in ternary expression


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?


Solution

  • 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
    }