在 Swift 3 中将 String 转换为 int

Posted

技术标签:

【中文标题】在 Swift 3 中将 String 转换为 int【英文标题】:Convert String to int in Swift 3 【发布时间】:2017-03-19 20:34:55 【问题描述】:

我有以下变量:

 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'

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

【问题讨论】:

How to initialize properties that depend on each other的可能重复 【参考方案1】:

更新

感谢 @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!)! ()

警告:如果在使用number1npill 仍然是nil,则此代码当然会崩溃。

旧版

你可以简单地写

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

【讨论】:

【参考方案2】:

(正如@Hamish 在下面的评论中指出的那样,我误解了 OP 真正要问的是什么。但是,我会留下我的答案,作为关于 ! 类型注释的一些好奇和见解,这可能与此问题的未来读者相关)


对于任何类型的 String 可选项,在使用可失败的 init?(_ text: String) 初始化程序或 Int 之前,需要解开它们的值。

在您的示例中,变量 npill 是可选的,因为您已使用 ! 说明符(应谨慎使用)注释其类型。引用已实施的evolution proposal SE-0054 [强调我的]

! 附加到 Swift 声明的类型将使其成为可选的 输入 并用一个属性注释声明 it 使用时可能会隐式展开

因此,将npill 直接与Intinit?(_ text: String) 初始化程序一起使用是完全合法的,因为它将在使用时即时解包(对nil 内容没有任何安全检查!)。

// UNSAFE example!
var npill: String! = "42"
if let npillInt = Int(npill) 
    /* ^^^^^^^^       ^^^^^- since 'npill' has a type annotated with
           |                 '!', it will be unsafely unwrapped at
           |                 this point                             
           \
          the optional binding here safely unwraps the return from
          the failable Int initializer, but has nothing to do with
          the unwrapping of 'npill'                                 */
    print(npillInt) // 42


// why unsafe? consider
npill = nil

if let npillInt = Int(npill)  // runtime exception!
    // ...

但是,通常您应该避免使用 ! 注释,除非您完全确定生成的可选变量的内容永远不会是 nil

撇开使用! 注释的缺点不谈:您可以通过使用安全显式展开技术覆盖不安全隐式展开来实现上述不安全示例的安全版本。对于使用 ! 注释声明的给定可选变量,我们仍然可以应用安全的方法来解包它,例如可选绑定或使用 nil 合并运算符。 @appzYourLife 已经展示了一种完全有效且安全的方法来处理 npill 的展开和类型转换尝试使用可选绑定,所以我将简单地包含另一个使用 nil 合并运算符的示例:

// "safe" example (STILL: why use the `!` annotation?)
var npill: String! = "42"
if let npillInt = Int(npill ?? "x") 
                /*    ^^^^^ if 'npill' is 'nil', the Int initializer will
                            be given the value "x", which itself will lead 
                            it to fail, which is safe here as we intend to
                            bind the result of the initialization to 'npillInt' */
    print(npillInt) // 42


npill = nil
if let npillInt = Int(npill ?? "x") 
    // ... doesnt enter

以上示例的共识是,如果我们稍微不确定npill 是否可以是nil,我们需要将其视为只是一个可选的未注释的类型!(即String?);使用变量时,使用安全方式覆盖默认的不安全展开。在这种情况下,我们为什么还要使用 ! typ 注解,因为它只会给我们的应用程序带来脆弱/危险?

【讨论】:

所有好的和有效的点 - 尽管 OP 遇到的问题是他试图从另一个属性的初始化程序访问实例属性,从错误消息“无法使用实例成员'npill'在属性初始化器中,属性初始化器在“self”可用之前运行" ;) @Hamish 啊,你是对的!似乎 appzYourLife 会更新他的答案,所以我会保留一些 ! 注释 curiosa :) 谢谢! @dfri:我们都犯了同样的错误。但是你的回答太棒了。你应该把它放在那里。

以上是关于在 Swift 3 中将 String 转换为 int的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 3 中将 NSData 转换为数据?

在 Swift 中将 Int 转换为 String

如何在swift中将'Date'类型的转换值返回为'String'

如何在swift中将字符索引从layoutManager转换为String scale

无法在 Swift 中将 String 转换为 Double [重复]

如何在 swift 3 中将具有自定义类的数组转换为 JSON