Swift proporciona varias formas de convertir un valor de string en un valor entero. Sin embargo, podemos convertir una string numérica solo en un valor entero. En este artículo, veremos los dos métodos más comunes que se utilizan para convertir una string en un valor entero. Una string es una colección de caracteres. Swift proporciona el tipo de datos String con la ayuda de los cuales podemos almacenar una string. Por ejemplo, «GeeksforGeeks», «GFG», etc. Una variable se puede declarar como tipo String siguiendo la siguiente sintaxis,
Sintaxis:
let myVariable: String
Por ejemplo: myVariable = “GeeksforGeeks”
Usando el inicializador Int
Swift proporciona la función de inicializadores de enteros mediante los cuales podemos convertir una string en un tipo Int. Para manejar strings no numéricas, podemos usar la fusión nula mediante la cual el inicializador de enteros devuelve un entero opcional.
let myStringVariable = «25»
let myIntegerVariable = Int(myStringVariable) ?? 0
Significa que si la string no es numérica, asigne 0 a la variable; de lo contrario, convierta la string numérica en un número entero. A continuación se muestra la implementación para convertir un String en Int:
Ejemplo:
Swift
// Swift program to convert String to Int // Here we are converting a numeric string. // Initializing a constant variable of string type let myStringVariable = "25" // Converting the string into integer type let myIntegerVariable = Int(myStringVariable) ?? 0 // Print the value represented by myIntegerVariable print("Integer Value:", myIntegerVariable) // Here, we are converting a non-numeric string. // Initializing a constant variable of string type let myStringvariable = "GeeksforGeeks" // Trying to convert "GeeksforGeeks" // to the integer equivalent but since // it's non-numeric string hence the // optional value would be assigned // to the integer variable which is // equal to 0 in this case let myIntegervariable = Int(myStringvariable) ?? 0 // Print the value represented by myIntegervariable print("Integer Value:", myIntegervariable)
Producción:
Integer Value: 25 Integer Value: 0
Usando NSString
NSString en Swift es una clase que se usa para crear objetos que se encuentran en el montón y se pasan por referencia. Proporciona diferentes tipos de métodos para comparar, buscar y modificar strings. Podemos convertir una string numérica en un valor entero indirectamente. En primer lugar, podemos convertir una string en un NSString, luego podemos usar la propiedad «integerValue» que se usa con NSStrings para convertir un NSString en un valor entero.
Ejemplo:
En el siguiente programa, hemos convertido la string numérica en NSString y luego hemos aplicado la propiedad «integerValue» para convertir una string en un valor entero.
Swift
// Swift program to convert String to Int import Foundation import Glibc let myString = "25" // Firstly we are converting a string into NSString then // using integerValue property we get integer value let myIntegerVariable = (myString as NSString) .integerValue print("Integer Value:", myString)
Producción:
Integer Value: 25