gpt4 book ai didi

swift - 在 Swift 3 中将字符串转换为整数

转载 作者:搜寻专家 更新时间:2023-11-01 07:18:30 26 4
gpt4 key购买 nike

我有以下变量:

 var npill : String!

这是一个 Int 值,但我不能将它设置为 Int,因为:

npillIn: fieldNumeroPillole.text!,

如何将此 var 转换为 Int var?我尝试了以下方法:

var number1: Int = (npill! as NSString).intValue

通过上面的代码,我收到以下错误:

cannot use instance member 'npill' within property initializer, property initializers run before "self" is aviable

如果我再设置:

var number1: Int = (self.npill! as NSString).intValue

它输出的错误如下:

Value of type '(NSObject) -> () -> Farmaco' has no member 'npill'

如果有人知道我应该如何正确转换它,请告诉我。

最佳答案

更新

感谢@Hamish 指出 OP 的要求

所以问题好像是这个

import Foundation

class Foo {
var npill : String!
var number1: Int = (npill! as NSString).intValue
}

error: cannot use instance member 'npill' within property initializer; property initializers run before 'self' is available
var number1: Int = (npill! as NSString).intValue
^

这是怎么回事?

您正在使用一个属性填充另一个属性,这是不允许允许的。

解决方案

但是,您可以轻松解决延迟 number1 初始化的问题。事实上,如果你让 number1 lazy,它只会在使用时被填充。

class Foo {
var npill : String!
lazy var number1: Int = { return Int(self.npill!)! }()
}

Warning: Of course this code will crash if npill is still nil when number1 is used.

旧版本

你可以简单地写

let npill: String! = "34"
if let npill = npill, let num = Int(npill) {
print(num) // <-- here you have your Int
}

关于swift - 在 Swift 3 中将字符串转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40449272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com