2017-04-23 61 views
0

我使用Swift和Vapor(服務器端)創建基本CRUD。Swift with Vapor:可選更新基於請求的模型字段

在我的控制器中,我創建了一個新的方法:「編輯」。在這種方法中,可以更新用戶的密碼和角色。 如果請求有密碼數據,更新密碼。 IF請求有一個新的角色數組,更新角色(兄弟姐妹關係至今尚未完成)。

這是在我的控制器中的「編輯」的方法:

func edit(request:Request, id:String) throws -> ResponseRepresentable { 
    // Check if the password came in POST request: 
    let password = request.data["password"]?.string 

    // Check if the request has a new set of roles 
    let roles = request.data["roles"]?.array 

    let user:ClinicUser = try ClinicUser.edit(id: id, password: password, roles: roles) 
    return user 
} 

而且在我的模型編輯方法是這樣的:

static func edit(id:String, password:String?, roles:Array<NodeRepresentable>?) throws -> ClinicUser { 
    guard var user:ClinicUser = try ClinicUser.find(id) else { 
     throw Abort.notFound 
    } 
    // Is it the best way of doing this? Because with "guard" I should "return" or "throw", right? 
    if password != nil { 
     user.password = try BCrypt.hash(password: password!) 
    } 

    // TODO: update user's roles relationships 

    try user.save() 

    return user 
} 

在我的控制,有通過指出錯誤表示Cannot convert value of type '[Polymorphic]?' to expected argument type 'Array<NodeRepresentable>'的XCode。而且,作爲修復,Xcode中提出這樣寫:

let user:ClinicUser = try ClinicUser.edit(id: id, password: password, roles: roles as! Array<NodeRepresentable>) 

我不知道這是否是安全的,或者如果這是一個最好的做法(強制解包與!)。

我不知道在Swift中我是否應該「思考」與其他語言(比如PHP等)不同。最後,我要的是:

static func edit(id:String, fieldA:String?, fieldN:String, etc..) throws -> ClinicUser { 
    // If fieldA is available, update fieldA: 
    if fieldA != nil { 
     model.fieldA = fieldA 
    } 

    // If fieldN is available, update fieldN: 
    if fieldN != nil { 
     model.fieldN = fieldN 
    } 

    // After update all fields, save: 
    try model.save() 

    // Return the updated model: 
    return model 
} 
+0

是xcode建議工作正常嗎? –

回答

0

在你的控制器,你可以做到以下幾點:

// Check if the request has a new set of roles 
let rolesArray = request.data["roles"]?.array 
guard let roles = rolesArray as? Array<NodeRepresentable> 
else { 
    // throw "SomeError" or return "Some other response" 
} 

Xcode的抱怨,因爲它不能說明你得到了數組類型您的請求數據在編譯時。

因此,您必須將其向下轉換爲更具體的類型。

您有兩種選擇。

  1. as! - >如果失敗會觸發運行時錯誤
  2. as? - >如果失敗會返回nil

那麼如果你使用as?並警惕,如果發生故障,您可以中斷您的功能執行並決定您想要執行的操作。