Value of type 'String' has no member '

2020-02-06 05:13发布

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:

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?

3条回答
Emotional °昔
2楼-- · 2020-02-06 05:30

You can try this as well.

let trimmedString = hex.trimmingCharacters(in: CharacterSet.whitespaces)
查看更多
Emotional °昔
3楼-- · 2020-02-06 05:40

Read the Swift 3 documentation; the new Swift 3 API is:

func trimmingCharacters(in set: CharacterSet) -> String

https://developer.apple.com/reference/swift/string/1643030-trimmingcharacters

查看更多
该账号已被封号
4楼-- · 2020-02-06 05:48

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.

查看更多
登录 后发表回答