简体   繁体   中英

Non-optional expression of type 'String' used in a check for optionals

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

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM