0

I am getting error

fatal error: Can't unwrap Optional.None
(lldb)

with this code

    var context:CGContextRef = UIGraphicsGetCurrentContext()
    let radius:CGFloat = 5
    CGContextSetRGBStrokeColor(context, 1, 1, 1, 1)
    var tempRect:CGRect = CGRectMake(5, 5, 20, 20)
    let minX = tempRect.minX, midX = tempRect.midX, maxX = tempRect.maxX
    let minY = tempRect.minY, midY = tempRect.midY, maxY = tempRect.maxY
    CGContextMoveToPoint(context, minX, minY)
    CGContextAddArcToPoint(context, minX, minY, midX, midY, radius)
    CGContextAddArcToPoint(context, maxX, minY, maxX, midY, radius)
    CGContextAddArcToPoint(context, maxX, maxY, midX, maxY, radius)
    CGContextAddArcToPoint(context, minX, maxY, minX, midY, radius)
    CGContextClosePath(context)
    CGContextDrawPath(context, kCGPathFillStroke)

I don't understand what the problem is. What I am trying to do is create a rectangle with rounded corners in Swift. Why am I getting this error and is there a much easier way to do this?

elito25
  • 624
  • 1
  • 6
  • 14

1 Answers1

0

The problem is that there is no current context. Thus UIGraphicsGetCurrentContext() would like to return NULL (nil). You should test context in a conditional before going on.

Also you should type context as a CGContext!, since that is what UIGraphicsGetCurrentContext() returns — a context, or nil, wrapped up in an Optional, implicitly unwrapped. Thus, when you get a context, you will be able to use it without using question marks everywhere. Even better, don't give it an explicit type at all; Swift knows better than you do what UIGraphicsGetCurrentContext() returns.

matt
  • 515,959
  • 87
  • 875
  • 1,141
  • And yes, there is a much easier way; use UIBezierPath. – matt Jun 12 '14 at 21:27
  • Isn't UIBezierPath mostly depreciated? Also, how do I pass in tempRect as context? – elito25 Jun 12 '14 at 21:47
  • (1) Why would you think UIBezierPath is deprecated? (2) You don't pass a rect as a context. You have a context or you don't. If you don't, you can't draw. If you do, it has a size. You might be asking how to _make_ a context; use UIGraphicsBeginImageContextWithOptions (if this context is ultimately supposed to become an image, that is). Or put your code in a place where Cocoa has already given you a context. See my full discussion of how to draw: http://www.apeth.com/iOSBook/ch15.html – matt Jun 12 '14 at 22:22