简体   繁体   English

如何在Swift中将字符串转换为Int?

[英]How to convert a String to an Int in Swift?

I'm trying to get the substring of the var num, but I need that substring be an Int How can I do that? 我正在尝试获取var num的子字符串,但是我需要将该子字符串作为一个Int怎么办?

This is my code 这是我的代码

func sbs_inicio(num: String, index: Int) -> Int{
    let dato: Int = num.index(num.startIndex, offsetBy: index)
    return dato
}

var num = "20932121133222"
var value = sbs_inicio(num: num, index: 2)
print(value) //value should be 20

Use the prefix function on the characters array 在字符数组上使用prefix函数

let startString = "20932121133222"
let prefix = String(startString.characters.prefix(2))
let num = Int(prefix)

Prefix allows you to get the first n elements from the start of an array, so you get these, convert them back to a String and then convert the resulting String to an Int 前缀允许您从数组的开头获取前n个元素,因此您可以获取它们,将它们转换回String ,然后将结果String转换为Int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM