Skip to content

Instantly share code, notes, and snippets.

@odrobnik
Last active August 29, 2015 14:25
Show Gist options
  • Select an option

  • Save odrobnik/529db10b7030c06e1bbd to your computer and use it in GitHub Desktop.

Select an option

Save odrobnik/529db10b7030c06e1bbd to your computer and use it in GitHub Desktop.
How to make this more elegant?
// Variant 1: looks inelegant
override internal func drawRect(rect: CGRect)
{
let context = UIGraphicsGetCurrentContext()
let size = bounds.size
if let gradient = gradient
{
let options = CGGradientDrawingOptions(kCGGradientDrawsAfterEndLocation)
var center = gradientStartPoint
if center == nil
{
center = CGPoint(x: bounds.midX, y: bounds.midY)
}
CGContextDrawRadialGradient(context, gradient, center!, 0, center!, min(size.width, size.height) / 2, options)
}
}
// Variant 2: bad because the CGContextDrawRadialGradient appears twice
override internal func drawRect(rect: CGRect)
{
let context = UIGraphicsGetCurrentContext()
let size = bounds.size
// Gradient
if let gradient = gradient
{
let options = CGGradientDrawingOptions(kCGGradientDrawsAfterEndLocation)
if let center = gradientStartPoint
{
CGContextDrawRadialGradient(context, gradient, center, 0, center, min(size.width, size.height) / 2, options)
}
else
{
let center = CGPoint(x: bounds.midX, y: bounds.midY)
CGContextDrawRadialGradient(context, gradient, center, 0, center, min(size.width, size.height) / 2, options)
}
}
}
@grantjbutler
Copy link
Copy Markdown

You should be able to use the nil coalescing operator (??) to clean up that assignment to center, and then not have to force unwrap it:

let center = gradientStartPoint ?? CGPoint(x: bounds.midX, y: bounds.midY)

Which cleans up the method nicely:

override internal func drawRect(rect: CGRect)
{
    let context = UIGraphicsGetCurrentContext()
    let size = bounds.size

    if let gradient = gradient
    {
        let options = CGGradientDrawingOptions(kCGGradientDrawsAfterEndLocation)
        let center = gradientStartPoint ?? CGPoint(x: bounds.midX, y: bounds.midY)

        CGContextDrawRadialGradient(context, gradient, center, 0, center, min(size.width, size.height) / 2, options)
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment