timpa
timpa

Reputation: 11

conditional cast from [Message] to [Message] always succeeds

if let context = delegate?.managedObjectContext {


        do {

      let fetchRequest = NSFetchRequest<Message>(entityName: "Message")

          let messages = try(context.fetch(fetchRequest) as? [Message])

This gives me the error "conditional cast from [Message] to [Message] always succeeds"

            for message in messages! {
                context.delete(message)

            }
            try(context.save())

        } catch let err {
            print (err)
        }

Can someone help me understand what I'm doing wrong?

Upvotes: 1

Views: 2950

Answers (1)

Sweeper
Sweeper

Reputation: 271800

Prior to swift 3, context.fetch() only returned an [AnyObject]. That was why you had to cast it like that.

But now in Swift 3, the NSFetchRequest class becomes generic and context.fetch() will return an array of the generic type you specified when creating the fetch request. It's much more type safe now.

Therefore, you don't need to cast it to the type you want anymore, because it already is that type!

let messages = try context.fetch(fetchRequest)

Upvotes: 4

Related Questions