2017-09-22 3 views
-1

스위프트 4 >> 연산자 스위프트 4.0 UIColor에 HexColor 변환하기위한 여분의 조작 구함 사용할 이다스위프트 4 >> 연산자 사용할

여기

스위프트 3.0 이전 코드 버전에 대한 샘플 코드이다.

public extension UIColor { 
    convenience init(hex: String) { 
     var red: CGFloat = 0.0 
     var green: CGFloat = 0.0 
     var blue: CGFloat = 0.0 
     var alpha: CGFloat = 1.0 

     if hex.hasPrefix("#") { 
      let index = hex.characters.index(hex.startIndex, offsetBy: 1) 
      let hex  = hex.substring(from: index) 
      let scanner = Scanner(string: hex) 
      var hexValue: CUnsignedLongLong = 0 
      if scanner.scanHexInt64(&hexValue) { 
       switch (hex.characters.count) { 
       case 3: 
        red = CGFloat((hexValue & 0xF00) >> 8)  /15.0 
        green = CGFloat((hexValue & 0x0F0) >> 4)  /15.0 
        blue = CGFloat(hexValue & 0x00F)   /15.0 
       case 4: 
        red = CGFloat((hexValue & 0xF000) >> 12) /15.0 
        green = CGFloat((hexValue & 0x0F00) >> 8) /15.0 
        blue = CGFloat((hexValue & 0x00F0) >> 4) /15.0 
        alpha = CGFloat(hexValue & 0x000F)   /15.0 
       case 6: 
        red = CGFloat((hexValue & 0xFF0000) >> 16) /255.0 
        green = CGFloat((hexValue & 0x00FF00) >> 8) /255.0 
        blue = CGFloat(hexValue & 0x0000FF)   /255.0 
       case 8: 
        red = CGFloat((hexValue & 0xFF000000) >> 24)/255.0 
        green = CGFloat((hexValue & 0x00FF0000) >> 16)/255.0 
        blue = CGFloat((hexValue & 0x0000FF00) >> 8)/255.0 
        alpha = CGFloat(hexValue & 0x000000FF)  /255.0 
       default: 
        print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "") 
       } 
      } else { 
//    print("Scan hex error") 
      } 
     } else { 
//   print("Invalid RGB string, missing '#' as prefix", terminator: "") 
     } 
     self.init(red:red, green:green, blue:blue, alpha:alpha) 
    } 
} 

미리 감사드립니다.

+3

은''>> 오퍼레이터가 아직 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AdvancedOperators.html 따르면 MCVE를 보여주십시오. – luk2302

+0

Swift 4에서 오류없이 저의 코드가 작동 중입니다. 오류가 있습니까? –

+0

@ViniApp - Swift 4에서 경고를받지 못했기 때문에 놀랍습니다. 이제'hex.substring (from : index)'구문이 더 이상 사용되지 않습니다. – Rob

답변

0

이 코드는 Swift 4의 >> 연산자에 문제가 없습니다. 유일한 문제는 문자열 처리입니다. (

  1. 내가 그것을 failable 초기화 할 것 : 나는 그 루틴에 대한 몇 가지 다른 변화를 만들 것, 개인적으로

    let index = hex.index(hex.startIndex, offsetBy: 1) 
    let hex  = String(hex[index...]) 
    

    let index = hex.characters.index(hex.startIndex, offsetBy: 1) 
    let hex  = hex.substring(from: index) 
    

    을 대체 할 수 예 : init?(...)은 선택 사항을 반환). 현재 호출 코드는 UIColor으로의 변환이 실패했는지 알 수있는 방법이 없습니다.

  2. 내가 그것을 감소, 위의 문자열 처리를 단순화 것 : 그 선행 # 선물을 제거하는 하나의 라인으로 줄일 수 있지만, 그것은 또한 의미 않습니다

    let hex = hex.replacingOccurrences(of: "^#", with: "", options: .regularExpression) 
    

    이뿐만 아니라이 코드는 것 이제는 #이없는 16 진수 문자열을 전달하면 작동합니다.

  3. 스캐너 대신 UInt64(_:radix:)을 사용하고 싶습니다. 조금 더 간단합니다. 따라서

:

public extension UIColor { 
    convenience init?(hex: String) { 
     var red: CGFloat = 0.0 
     var green: CGFloat = 0.0 
     var blue: CGFloat = 0.0 
     var alpha: CGFloat = 1.0 

     let hex = hex.replacingOccurrences(of: "^#", with: "", options: .regularExpression) 
     guard let hexValue = UInt64(hex, radix: 16) else { 
      print("invalid hex string") 
      return nil 
     } 

     switch (hex.count) { 
     case 3: 
      red = CGFloat((hexValue & 0xF00) >> 8)  /15.0 
      green = CGFloat((hexValue & 0x0F0) >> 4)  /15.0 
      blue = CGFloat(hexValue & 0x00F)   /15.0 
     case 4: 
      red = CGFloat((hexValue & 0xF000) >> 12) /15.0 
      green = CGFloat((hexValue & 0x0F00) >> 8) /15.0 
      blue = CGFloat((hexValue & 0x00F0) >> 4) /15.0 
      alpha = CGFloat(hexValue & 0x000F)   /15.0 
     case 6: 
      red = CGFloat((hexValue & 0xFF0000) >> 16) /255.0 
      green = CGFloat((hexValue & 0x00FF00) >> 8) /255.0 
      blue = CGFloat(hexValue & 0x0000FF)   /255.0 
     case 8: 
      red = CGFloat((hexValue & 0xFF000000) >> 24)/255.0 
      green = CGFloat((hexValue & 0x00FF0000) >> 16)/255.0 
      blue = CGFloat((hexValue & 0x0000FF00) >> 8)/255.0 
      alpha = CGFloat(hexValue & 0x000000FF)  /255.0 
     default: 
      print("Invalid RGB string, number of characters after '#' should be either 3, 4, 6 or 8", terminator: "") 
      return nil 
     } 

     self.init(red: red, green: green, blue: blue, alpha: alpha) 
    } 
}