-1

I am getting this warning from Xcode Swift 5, here is my code I don't get what is wrong, I use this to remove any new line or tab at the end of my String (line)

My code:

let url: String = String(line.filter { !" \n\t\r".contains($0) })

UPDATE

I was doing it inside an if let and was using the type cast operator here is the solution and the rest of code and an example of the line value.

let line = " http://test.com/testing.php \n"
if let url: String = line.filter({!" \n\t\r".contains($0)}) as String?
{
       //More action here
}

Thank you

  • If you enter that code in a playground by itself (with some definition of `line`) do you still get the error? – Phillip Mills Jan 14 '20 at 18:44
  • 2
    What is `line`? A self-contained [mcve] and the exact error message would be helpful. – Martin R Jan 14 '20 at 18:44
  • Does this answer your question? [Swift 3 warning: Non-optional expression of type 'String' used in a check for optionals](https://stackoverflow.com/questions/40884167/swift-3-warning-non-optional-expression-of-type-string-used-in-a-check-for-op) – koen Jan 14 '20 at 18:45
  • The correct solution would be to remove the (unnecessary) optional binding, not to add an artificial cast `as String?`. – Martin R Jan 14 '20 at 19:58

1 Answers1

0

to me this line looks good, but you may be missing the parentheses for the string filter method. Here's two ways I did it in playground. Let me know if this works for you, or how I can help further.

var line = "\t Hello, line removal \n \t Another new line \n"

let filteredClosure = line.filter { (char) -> Bool in
    return !"\n\t\r".contains(char)
}

let filterShorthand = line.filter({!"\n\t\r".contains($0)})

With the line you provided, I would expect white-space to be removed too. If that's what you're looking for, add a space inside the filter string: " \n\t\r"

jnblanchard
  • 1,182
  • 12
  • 12