1) Il primo codice funziona perché String
ha un metodo init che accetta uno Int
. Poi sulla linea
let widthLabel = label + String(width)
Stai concatenazione le corde, con l'operatore +
, per creare widthLabel
.
2) messaggi di errore Swift può essere molto fuorviante, il vero problema è Int
non ha un metodo che prende un init
String
. In questa situazione è possibile utilizzare il metodo toInt
su String
. Ecco un esempio:
if let h = height.toInt() {
let heightNumber = number + h
}
si dovrebbe usare e if let
dichiarazione per controllare la String
può essere convertito in un Int
dal toInt
tornerà nil
se non riesce; forzare lo srotolamento in questa situazione causerà il crash della tua app. Vedere il seguente esempio di cosa accadrebbe se height
non era convertibile in una Int
:
let height = "not a number"
if let h = height.toInt() {
println(number + h)
} else {
println("Height wasn't a number")
}
// Prints: Height wasn't a number
Swift 2.0 Update:
Int
ora ha un initialiser che prende un String
, rendendo ad esempio 2 (vedi sopra):
if let h = Int(height) {
let heightNumber = number + h
}
Vedere anche la risposta a [questa domanda] (http: //stackoverflow.com/questions/40557214/swift-operator-throwing-error-on-two-ints). In sostanza, se A è già dichiarato come Double di CGFloat o qualsiasi cosa, e B e C sono interi, A = B + C fallirà con questo messaggio di errore, che oscura il vero problema e la soluzione: A = Double (B + C) . Questa domanda/risposta è in cima alla ricerca di Google per questo errore; in alcuni casi, la risposta dell'altra domanda potrebbe essere più utile. – ConfusionTowers