2016-11-04 96 views
0

在ViewController中,我有三個文本字段(郵件,密碼,重複密碼)。在將數據發送到服務器之前,我會做一些驗證(檢查文本是否存在,郵件是否有效等)。TextField輸入驗證模式

我這樣做是這樣的:

let email = emailTextfield.text 
let password = passwordTextfield.text 
let repeatPassword = repeatPasswordTextfield.text 

     if let e = email { 
      if let p = password { 
       if let rp = repeatPassword{ 

        if(e.isEmpty || p.isEmpty || rp.isEmpty){//cut mail validation... 

的問題是:這是做到這一點的最好方法是什麼?有沒有更好的(也許更緊湊)的方式?提前致謝。

回答

1

從Swift 2.0開始,您不再需要構造an optional binding pyramid of doom,但可以在同一個if陳述中使用多個綁定(以及布爾條件)。例如:

if let email = emailTextfield.text, !email.isEmpty, 
    let password = passwordTextfield.text, !password.isEmpty, 
    let repeatPassword = repeatPasswordTextfield.text, !repeatPassword.isEmpty { 
    // proceed only for all non-nil and non-empty above ... 
} 

這些將首先失敗綁定/ false有條件會自然短路。

+0

但它只是另一種金字塔! ;-) –

+1

@IanBell在這種情況下,我不會真正將它稱爲金字塔:我們不必輸入if塊的嵌套級別(因爲Swift 2.0之前的用戶不得不受此影響)。也許這是更廣泛的基礎平臺,而不是? :) – dfri

+1

我在開玩笑:-) –

0

你可以做 if email?.isEmpty || password?.isEmpty || repeatPassword?.isEmpty { //break }

不要擔心零值,讓它作爲optionnal,一切都會好起來的。

+0

但在某個時刻,我必須將該值發送到服務器,不應該解開? –

+1

好吧,你可以在一個變量中進行賦值:'if let ...,...,...' –

1

我不知道,但我可以看到兩個解決方案:

-The第一個是清晰的:

if let e = email, let p = password, let rp = repeatPassword { 
    if e.isEmpty || p.isEmpty || rp.isEmpty { 
     // do your things 
    } 
} 

-the第二個是更緊湊:

if email != nil, password != nil, repeatPassword != nil, (email!.isEmpty || password!.isEmpty || repeatPassword!.isEmpty) { 
    // do the things force unwrapping every variable 
} 

第二解決方案工作,因爲如果電子郵件或密碼或repeatPassword是零,編譯器將不會繼續閱讀條件,因此不會崩潰閱讀例如repeatPassword!.isEmpty爲nil.isEmpty

要建立在@dfri的回答,我能想到這個解決方案(非測試)的:

if let e = email, let p = password, let rp = repeatPassword, (e.isEmpty, p.isEmpty, rp.isEmpty) { 
    // cut mail validation 
} 

最後一個,如果作品,顯然是最優雅的解決方案,我會刪除它只要@dfri更新他的解決方案,以遵守您的答案:)

1
if let email = emailTextfield.text where !email.isEmpty, 
    let password = passwordTextfield.text where !password.isEmpty, 
    let repeatPassword = repeatPasswordTextfield.text where !repeatPassword.isEmpty { 
    // Go for it. 
} 
+2

請注意,這是[_exactly_答案](http://stackoverflow.com/a/40426153/4573247)我已經發布,但使用不贊成的語法('.. where')。 – dfri

+1

是的,但是從何時開始棄用? – NRitH

+1

從Swift 3.0開始,請參閱進化方案[SE-0099:重構條件子句](https://github.com/apple/swift-evolution/blob/master/proposals/0099-conditionclauses.md)(請注意,上面的代碼不能編譯Swift> = 3.0)。 – dfri