2017-12-14 15 views
0

"값을 할당 할 수 없습니다 '자체가'불변"신속한 UIColor 확장 : 내가 직접 알파를 변경하는 <code>UIColor</code>의 확장을 썼다

public extension UIColor { 

    public var rgbaComponents: (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat) { 
     var components: [CGFloat] { 
      let c = cgColor.components! 
      if c.count == 4 { 
       return c 
      } 
      return [c[0], c[0], c[0], c[1]] 
     } 
     let r = components[0] 
     let g = components[1] 
     let b = components[2] 
     let a = components[3] 
     return (red: r, green: g, blue: b, alpha: a) 
    } 

    public var alpha: CGFloat { 
     get { 
      return cgColor.alpha 
     } 
     set { 
      var rgba = rgbaComponents 
      self = UIColor(red: rgba.red // error here: "cannot assign to value: 'self' is immutable" 
      , green: rgba.green, blue: rgba.blue, alpha: newValue) 
     } 
    } 
} 

을하지만 오류가 :

cannot assign to value: 'self' is immutable

은 그것은 그러나 자기에 할당 할 날짜의 확장

public extension Date { 

    public var day: Int { 
     get { 
      return Calendar.current.component(.day, from: self) 
     } 
     set { 
      let allowedRange = Calendar.current.range(of: .day, in: .month, for: self)! 
      guard allowedRange.contains(newValue) else { return } 

      let currentDay = Calendar.current.component(.day, from: self) 
      let daysToAdd = newValue - currentDay 
      if let date = Calendar.current.date(byAdding: .day, value: daysToAdd, to: self) { 
       self = date // This is OK 
      } 
     } 
    } 
} 

OK 때문에의 UIColor이 이리저리이다 m NSObject 날짜가 Swift 구조체입니까? 근본 원인은 무엇입니까?

답변

1

Date가 struct (값 유형)이고 UIColor가 클래스 (참조 유형)이기 때문에 정확합니다.

struct에 self를 지정하면 실제 메모리 위치가 변경되지 않도록 해당 구조의 모든 속성을 업데이트하는 것입니다. 그래서 당신은 실제로 자기 자신의 가치를 돌연변이시키는 것이 아닙니다.

그러나 클래스에 대해 self에 할당하면 완전히 새로운 클래스가 메모리에 만들어 지므로 자신을 할당하면 자신을 변경하려고합니다. 허용 된 경우에도 색상에 대한 참조를 보유하고있는 것이 어떻게 원래 클래스에 대한 참조를 보유하고있는 것처럼 처리 할 수 ​​있습니까?

+0

코드로 솔루션을 게시 할 수 있습니까? @Upholder –

+0

불행히도 확장 기능을 사용하는 솔루션이 없다고 생각합니다. 새로운 것을 만들지 않고는'UIColor'의 알파를 변경할 수 없으며, 변경할 수 없으므로 자기를 바꿀 수 없습니다. –

+0

대단히 감사합니다! – Phoenix19