【发布时间】:2017-12-14 08:36:54
【问题描述】:
我写了一个UIColor的扩展来直接改变alpha:
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)
}
}
}
但是有一个错误:
无法赋值:'self' 是不可变的
但是将日期延长以分配给自己是可以的
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
}
}
}
}
是因为 UIColor 来自 NSObject 并且 Date 是一个 Swift 结构吗?根本原因是什么?
【问题讨论】:
标签: swift struct extension-methods nsobject