ios 'String' 类型的值没有成员 'stringByTrimmingCharactersInSet'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38644568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Value of type 'String' has no member 'stringByTrimmingCharactersInSet'
提问by Robert Tillman
After converting my project to swift 3, I get the following Value of type 'String' has no member 'stringByTrimmingCharactersInSet'
error on the first line within this block:
将我的项目转换为 swift 3 后,我Value of type 'String' has no member 'stringByTrimmingCharactersInSet'
在此块的第一行收到以下错误:
extension UIColor {
convenience init (hex:String) {
var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercased() // error appears on this line
if (cString.hasPrefix("#")) {
cString = (cString as NSString).substring(from: 1)
}
let rString = (cString as NSString).substring(to: 2)
let gString = ((cString as NSString).substring(from: 2) as NSString).substring(to: 2)
let bString = ((cString as NSString).substring(from: 4) as NSString).substring(to: 2)
var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
Scanner(string: rString).scanHexInt32(&r)
Scanner(string: gString).scanHexInt32(&g)
Scanner(string: bString).scanHexInt32(&b)
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
}
}
I'm guessing the error derives from a change in syntax with 'stringByTrimmingCharactersInSet'
.. what is the correction for this?
我猜这个错误'stringByTrimmingCharactersInSet'
是由于语法的变化而产生的.. 对此有何更正?
回答by Vladimir Nul
The new syntax is like this:
新的语法是这样的:
var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()
As a suggestion, you don't need to specify that cString
is a String, as this is assumed with the value you are assigning to it.
作为建议,您不需要指定它cString
是一个字符串,因为这是假定您分配给它的值。
回答by Vishnu Gupta
You can try this as well.
你也可以试试这个。
let trimmedString = hex.trimmingCharacters(in: CharacterSet.whitespaces)
回答by dannyzlo
Read the Swift 3 documentation; the new Swift 3 API is:
阅读 Swift 3 文档;新的 Swift 3 API 是:
func trimmingCharacters(in set: CharacterSet) -> String
https://developer.apple.com/reference/swift/string/1643030-trimmingcharacters
https://developer.apple.com/reference/swift/string/1643030-trimmingcharacters