无法在swift中比较/返回nil对象

时间:2016-03-21 05:38:21

标签: ios swift core-data

我不是Objective-C的新手,但我是swift的新手。我曾经比较过对象,如果它们在Objective-C中为零,但我无法在swift中做到这一点。

func getCurrentUser() -> Users{

    let fetchRequest = NSFetchRequest(entityName: "Users")
    var fetchedUsers = NSArray()
    do {
        let fetchedEntities = try self.managedObjectContext.executeFetchRequest(fetchRequest) as NSArray
        fetchedUsers = fetchedEntities
    } catch {
        // Do something in response to error condition
    }

    var userToSend = Users()

    for user in fetchedUsers{

        let currentUser = user as! Users
        if(currentUser.isSignedIn == 1)
        {
            userToSend = currentUser
            break
        }
    }
    return userToSend
}

如果我的userToSend为nil,我无法检查调用方法的位置,代码崩溃。

这是我的代码崩溃的地方:

    let currentUser = UserDBService().getCurrentUser()

    let userID = String(currentUser.userId)

我怎么能这样做?

更新

我使用了迈克尔的答案,但我仍然崩溃了:

enter image description here

使用了Eendje的解决方案,我明白了:

enter image description here

4 个答案:

答案 0 :(得分:3)

func getCurrentUser() -> Users? {
    let fetchRequest = NSFetchRequest(entityName: "Users")
    let fetchedUsers = (try? managedobjectContext.executeFetchRequest(fetchRequest)) as? [Users] ?? []

    // If there are no instances of Users with isSignedIn == 1, it returns nil
    guard let index = fetchedUsers.indexOf({ $0.isSignedIn == 1 }) else { return nil }

    // Since it passed the guard, it can return the user
    return fetchedUsers[index]
}

// Returns an optional String
let userID = String(getCurrentUser()?.userID)

重写了一下你的功能,这应该可以工作。

答案 1 :(得分:1)

阐述我的评论,看起来getCurrentUser应该返回一个Optional:

func getCurrentUser() -> Users? {

    let fetchRequest = NSFetchRequest(entityName: "Users")
    var fetchedUsers = NSArray()
    do {
        let fetchedEntities = try self.managedObjectContext.executeFetchRequest(fetchRequest) as NSArray
        fetchedUsers = fetchedEntities
    } catch {
        // Do something in response to error condition
    }

    for user in fetchedUsers {
        if let currentUser = user as? Users {
            if(currentUser.isSignedIn == 1) {
                return currentUser
            }
        }
    }
    return nil
}

然后你会把它称为:

if let currentUser = UserDBService().getCurrentUser() {
    let userID = String(currentUser.userId)
} else {
    // no current user
}

答案 2 :(得分:1)

你可以用任何方式修复此崩溃

if let currentUser = UserDBService().getCurrentUser() {
    let userID = String(currentUser.userId)
} else {

}

OR

 let currentUser = UserDBService().getCurrentUser()
     if(currentUser!=nil){
        let userID = String(currentUser.userId)
     }else{
        // Nil handling code
     }

答案 3 :(得分:0)

    func getCurrentUser() -> Users? {
        let fetchRequest = NSFetchRequest(entityName: "Users")
        let fetchedUsers = (try? managedobjectContext.executeFetchRequest(fetchRequest)) as? [Users] ?? []

     returns nil
        guard let index = fetchedUsers.indexOf({ $0.isSignedIn == 1 }) 
        else 
        { 
            return nil 
        }

        return fetchedUsers[index]
    }

//Call your method like this
let userID = String(getCurrentUser(context)?.userID)

如果您使用的是共享上下文,或者您拥有context,请在此处使用self.context,删除self.context