Für Swift 3 und Swift 4.
Einfacher Weg: hart codiert. Nur nützlich, wenn Sie genau wissen, wie viele Ganzzahlen angezeigt werden, wie Sie berechnet und gedruckt/weiter verwendet werden sollen.
let string98: String = "98"
let string99: String = "99"
let string100: String = "100"
let string101: String = "101"
let int98: Int = Int(string98)!
let int99: Int = Int(string99)!
let int100: Int = Int(string100)!
let int101: Int = Int(string101)!
// optional chaining (if or guard) instead of "!" recommended. therefore option b is better
let finalInt: Int = int98 + int99 + int100 + int101
print(finalInt) // prints Optional(398) (optional)
Fancy Art und Weise als Funktion: Allgemein Weg. Hier können Sie am Ende so viele Strings einfügen, wie Sie benötigen. Sie könnten zum Beispiel zuerst alle Zeichenfolgen sammeln und dann das Array verwenden, um sie berechnen zu lassen.
func getCalculatedIntegerFrom(strings: [String]) -> Int {
var result = Int()
for element in strings {
guard let int = Int(element) else {
break // or return nil
// break instead of return, returns Integer of all
// the values it was able to turn into Integer
// so even if there is a String f.e. "123S", it would
// still return an Integer instead of nil
// if you want to use return, you have to set "-> Int?" as optional
}
result = result + int
}
return result
}
let arrayOfStrings = ["98", "99", "100", "101"]
let result = getCalculatedIntegerFrom(strings: arrayOfStrings)
print(result) // prints 398 (non-optional)
Bitte fügen Sie eine Erklärung dafür, wie Ihr Code funktioniert. – brimstone
und wie ist das anders als meine Antwort? –