Value of type 'String' has no member 'stringByTrimmingCharactersInSet'

28,951

Solution 1

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.

Solution 2

You can try this as well.

let trimmedString = hex.trimmingCharacters(in: CharacterSet.whitespaces)
Share:
28,951

Related videos on Youtube

Robert Tillman
Author by

Robert Tillman

Updated on July 09, 2022

Comments

  • Robert Tillman
    Robert Tillman almost 2 years

    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?

    • matt
      matt almost 8 years
      You should be asking yourself why you can't discover the answer on your own.
    • Hamish
      Hamish almost 8 years
      Have you tried typing in hex.trim and seeing what the auto-complete finds for you? Or looking at the "Apply API Guidelines to the Standard Library" evolution proposal?
  • Yunnosch
    Yunnosch over 3 years
    This post doesn't look like an attempt to answer this question. Every post here is expected to be an explicit attempt to answer this question; if you have a critique or need a clarification of the question or another answer, you can post a comment (like this one) directly below it. Please remove this answer and create either a comment or a new question. See: Ask questions, get answers, no distractions