2015-05-19 17 views
8

In Swift, come si può verificare se una stringa è un doppio valore valido? Sono stato con la seguente estensione da this question (ma come un galleggiante), ma se il valore non può essere convertito, restituisce semplicemente "0":Controlla se la stringa è un doppio valore valido in Swift

extension String { 
    var doubleValue:Double? { 
     return (self as NSString).doubleValue 
    } 
} 

Idealmente, desidero per tornare nil modo che possa essere catturati in un if-let, in questo modo:

if let i = str.doubleValue { 
    object.price = i 
} else { 
    // Tell user the value is invalid 
} 
+0

se (numero - piano (numero)> 0.000001) {// 0.000001 può essere modificato a seconda del livello di precisione è necessario // valore doppio } Try questo fuori? È venuto da qui http://stackoverflow.com/questions/25552648/check-if-number-is-decimal-with-swift – Wraithseeker

risposta

10

E 'infatti più efficiente non creare un numero formattatore ogni volta che facciamo una conversione:

extension String { 
    struct NumFormatter { 
     static let instance = NumberFormatter() 
    } 

    var doubleValue: Double? { 
     return NumFormatter.instance.number(from: self)?.doubleValue 
    } 

    var integerValue: Int? { 
     return NumFormatter.instance.number(from: self)?.intValue 
    } 
} 
+2

Se si sta percorrendo questa rotta, qualsiasi motivo per non rendere la struttura un membro di prima classe dell'intera estensione di classe ? Quindi puoi facilmente estendere la stringa per supportare anche 'integerValue',' boolValue', ecc. E condividere lo stesso 'formatter'. –

+1

@BlakeMerryman sono d'accordo, codice di esempio aggiornato – andriys

+1

Nota per gli altri: NSNumberFormatter() è stato rinominato in NumberFormatter in Swift 3 in modo che il nome della struttura fornisca errori. Tutto quello che devi fare è cambiarlo. –

19

aggiornamento: Xcode 7.1.1 • Swift 2.1

È possibile utilizzare doppio initialiser doppia (stringa :) per creare un interno e usarlo per controllare se la stringa è un doppio valida come segue:

extension String { 
    var doubleValue: Double? { 
     return Double(self) 
    } 
    var floatValue: Float? { 
     return Float(self) 
    } 
    var integerValue: Int? { 
     return Int(self) 
    } 
} 

Testing

let str = "b" 
if let value = str.doubleValue { 
    print(value) 
} else { 
    print("invalid input") 
} 
+3

Ti suggerirei di memorizzare nella cache NSNumberFormatter, se usi molto questo metodo (ad esempio su tableViewCell) trarrai vantaggio dalla memorizzazione nella cache. – EmilioPelaez

+0

@EmilioPelaez Come andresti a metterlo in cache? – Fengson

+0

@Fengson la sua domanda è stata fatta quando la risposta era in Swift 1 e al momento non c'era alcun inizializzatore Double (stringa _ :). questa risposta mostra come farlo in Swift 3.xe successive https://stackoverflow.com/a/27705739/2303865 –

-5

Qui è la mia funzione:

func je_numerik(text:Character)->Bool //en znak 
{ 
    if((text=="0")||(text=="1")||(text=="2")||(text=="3")||(text=="4")||(text=="5")||(text=="6")||(text=="7")||(text=="8")||(text=="9")){ 
     return true 
    } 
    else 
    { 
     return false 
    } 
} 

func je_stevilka(text: String)->Bool 
{ 
    var pika:Character 
    pika="." 

    var je_stevilka=true 
    //var znaki = Character(text) 
    var znaki=Array(text) 
    var stevilo_znakov=znaki.count 

    if(stevilo_znakov==0) 
    { 
     je_stevilka=false 
    } 
    else 
    { 
     if(stevilo_znakov==1) 
     { 
      if(je_numerik(znaki[0])) 
      { 
       je_stevilka=true 
      } 
      else 
      { 
       je_stevilka=false 
      } 
     } 
     else 
     { 

      if((je_numerik(znaki[0])) && (!((znaki[0]=="0")&&((znaki[1]=="0"))))&&(!((znaki[0]=="0")&&((je_numerik(znaki[1])))))) 
      { 

       var je_pika=false 
       for var i = 0; i < stevilo_znakov; i++ 
       { 
        if(je_numerik(znaki[i])||(znaki[i]==pika)) 
        { 
         if(znaki[i]==pika) 
         { 
          if(je_pika) 
          { 
           je_stevilka=false 
          } 
          else 
          { 
           je_pika=true 
           if(stevilo_znakov==(i+1)) 
           { 
            je_stevilka=false 
           } 
          } 
         } 
        } 
        else 
        { 
         je_stevilka=false 
        } 
       } 
      } 
      else 
      { 
       je_stevilka=false 
      } 
     } 
    } 

    return je_stevilka 
} 

Basta chiamare in questo modo:

var check_if_is_number=je_stevilka(numberText) 
+0

è un cattivo modello per utilizzare la custodia del serpente per lo sviluppatore rapido, controlla la custodia del cammello. –

Problemi correlati