johann
johann

Reputation: 1135

Swift2: return a optional type object

I'm new in the swift2 world and I currently struggle with a simple function :

// Get all moves for the first category
func getMuscles() -> BodyPart {

        let bpart:BodyPart?

        if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {
            do{
                let fetchRequest = NSFetchRequest(entityName: "BodyPart")
                let fetchResults = try managedObjectContext.executeFetchRequest(fetchRequest) as! [BodyPart]
                bpart = fetchResults[0]
            } catch let error as NSError  {
                print(error)
                bpart = nil
            }
        }
        return bpart
}

function in swift2

How can I solve this issue ? And what are the 'best-practices' in swift2 for defining a function ?

Thank you


EDIT 1

I've tried to change the signature of the method, but error is still here :

enter image description here

Upvotes: 0

Views: 119

Answers (4)

Tsimmi
Tsimmi

Reputation: 1868

The question you should be asking yourself is whether getMuscles() must always return an object or if it's fine for it to return a nil.

By changing the method signature to func getMuscles() -> BodyPart?, you're basically stating that a nil might be returned from that method, thus solving your immediate compile time issue.

In that particular context, because you're fetching objects from CoreData, it might be wise to allow getMuscles() to return a nil.

The way you define your functions (if they return optionals ?, or not) entirely depends on the calling code.

Upvotes: 4

user4790024
user4790024

Reputation:

Thats nothing to do with SWIFT2.. The return type is expecting some value BodyPart not an optional value BodyPart?...But you are returning a optional value bpart

func getMuscles() -> BodyPart {

        let bpart:BodyPart?

      ....
        return bpart
}

If you want to return bpart as it is you need to create the return type as optional

func getMuscles() -> BodyPart? {

        let bpart:BodyPart?

      ....
        return bpart
}

or if you want to just return the value try this

func getMuscles() -> BodyPart {

        let bpart:BodyPart = ()//initialize here dont make optional

      ....
        return bpart
}

Upvotes: 1

orkoden
orkoden

Reputation: 19996

Just return:

func getMuscles() -> BodyPart? { }

Upvotes: 1

Muneeba
Muneeba

Reputation: 1776

Change your method signature to : func getMuscles() -> BodyPart?

But be careful while unwrapping the return value when the this function is being called.

Upvotes: 1

Related Questions