简体   繁体   English

用于检查选项的“字符串”类型的非可选表达式

[英]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)我从 Xcode Swift 5 收到此警告,这是我的代码

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.我在if let中执行此操作,并在此处使用类型转换运算符,这是解决方案和其余代码以及行值示例。

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"如果这就是您要查找的内容,请在过滤器字符串中添加一个空格: “\\n\\t\\r”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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