Greg Greg - 3 months ago 12
Swift Question

how to use values returned by Swift function

I am trying to use a Swift function to place a circle in the centre of a view so it is always on centre regardless of screen size. I can draw the circle at a point defined by a set of arbitrary x and y values but I need the function to supply these values instead.

I have created a function called

to read and return two parameters that are the centre coordinates. However Xcode warns that the

“Result of call to screenCentre() is unused”

I’ve worked through Swift tutorials on functions and closures and understand how to pass arguments to a function but I am still not clear how to use values returned by this function.

Here is my code:

import UIKit

class ViewController: UIViewController {

let radius = CGFloat(20)
let fillColour = UIColor.clear.cgColor
let lineColour =
let lineWidth = 1.0

var x: CGFloat?
var y: CGFloat?

override func viewDidLoad() {


// arbitrary set of coordinates used to draw circle

circle(x: 150, y: 170)


func screenCentre() -> (x: CGFloat, y: CGFloat)
return (self.view.bounds.size.width / 2, self.view.bounds.size.height / 2)

func circle(x: CGFloat, y: CGFloat) {
let circlePath = UIBezierPath(arcCenter: CGPoint(x: x,y: y), radius: radius, startAngle: CGFloat(0), endAngle:CGFloat(M_PI * 2), clockwise: true)

let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath

shapeLayer.fillColor = fillColour
shapeLayer.strokeColor = lineColour
shapeLayer.lineWidth = CGFloat(lineWidth)



By declaring a constant I am able to use values returned by this function. Sam_M answered the question as asked.

However Daniel T and PEEJWEEJ both identified a related problem I hadn’t recognised. Once I applied fixits the extension solution offered by Daniel T now gives me a way to rotate the screen around the centre. So I marked it as the best answer. Thanks to everyone who contributed.

Here is the updated code.

let centre = UIScreen.main.centre
circle(x: centre.x, y: centre.y)

func screenCentre() -> CGPoint {
return CGPoint(x: UIScreen.main.bounds.midX, y: UIScreen.main.bounds.midY)


Your screenCentre() function won't work in viewDidLoad because the view is not yet sized to the screen, therefore its center is not in the middle of the screen.

Use this instead:

func screenCentre() -> CGPoint {
    return CGPoint(x: UIScreen.mainScreen().bounds.midX, y: UIScreen.mainScreen().bounds.midY)

Note that I am using a CGPoint instead of a tuple, but the effect is the same. Also, the above function doesn't need to be in your view controller or any other class since it doesn't reference self. It can be a global function.

Since Swift style guidelines encourage making methods over global functions, you might prefer to put the function in an extension like this:

extension UIScreen {
    var centre: CGPoint {
        return CGPoint(x: bounds.midX, y: bounds.midY)

Which can be called like this:

let centre = UIScreen.mainScreen().centre