类型的值'字符串'没有会员' stringByTrimmingCharactersInSet'

时间:2016-07-28 18:53:41

标签: ios swift xcode swift3

将我的项目转换为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))
    }
} 

我猜测错误源自'stringByTrimmingCharactersInSet'语法的变化..对此有何修正?

4 个答案:

答案 0 :(得分:36)

新语法是这样的:

var cString = hex.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).uppercased()

作为建议,您不需要指定cString是一个字符串,因为这是假设您分配给它的值。

答案 1 :(得分:1)

您也可以试试这个。

let trimmedString = hex.trimmingCharacters(in: CharacterSet.whitespaces)

答案 2 :(得分:0)

阅读Swift 3文档;新的Swift 3 API是:

func trimmingCharacters(in set: CharacterSet) -> String

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

答案 3 :(得分:0)

对于Int和Float,如何编码?

    private var currentTotal_passengers: Int = 0 {
    didSet {
        currentTotal_passengers = currentTotal_passengers.trimmingCharacters(in: CharacterSet .whitespacesAndNewlines)
    }
}