简体   繁体   English

在Swift 3中将String转换为int

[英]Convert String to int in Swift 3

I have the following variable: 我有以下变量:

 var npill : String!

It's an Int value, but I can't set it as Int because of: 这是一个Int值,但是由于以下原因,我无法将其设置为Int:

npillIn: fieldNumeroPillole.text!,

How can I convert this var to a Int var? 如何将此var转换为Int var? I have tried the following: 我尝试了以下方法:

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

By the above code I receive the following error: 通过以上代码,我收到以下错误:

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

If I then set: 如果我再设定:

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

The error it outputs is as follows: 它输出的错误如下:

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

If anyone knows how I should be converting it properly, please let me know. 如果有人知道我应该如何正确转换它,请告诉我。

Update 更新

Thank you to @Hamish for pointing out what the OP was asking 感谢@Hamish指出OP的要求

So the problem seems to be this 所以问题似乎是这样

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
                    ^

What's going on here? 这里发生了什么?

You are using a property to populate another property, and this is not allowed. 您正在使用一个属性来填充另一个属性,这是不允许的。

Solution

However you can easily fix the problem postponing the initialisation of number1 . 但是,您可以轻松地解决延迟number1初始化的问题。 Infact if you make number1 lazy , it will be populated only when used. 实际上,如果将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. 警告:当然,当使用number1时,如果npill仍为nil ,则此代码将崩溃。

Old version 旧版本

You can simply write 你可以简单地写

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

(As @Hamish pointed out in a comment below, I misunderstood what the OP was really asking about. I'll leave my answer, however, as some curiosa and insights regarding ! type annotation, which may be relevant for future readers of this question) (正如@Hamish在下面的评论中指出的那样,我误解了OP真正要问的问题。不过,我会留下我的答案,因为有一些关于!类型注释的古玩和见解,这可能与将来该问题的读者有关)


For any type of String optionals, their values needs to be unwrapped prior to using the failable init?(_ text: String) initializer or Int . 对于任何类型的String可选对象,在使用失败的init?(_ text: String)初始值设定项或Int之前,必须先解开其值。

In your example, the variable npill is an optional, as you've annotated its type with the ! 在您的示例中,变量npill是可选的,因为您已经用!注释了它的类型! specifier (which should be used with care). 说明符(应谨慎使用)。 Quoting from the implemented evolution proposal SE-0054 [ emphasis mine ] 引用已实施的发展建议SE-0054 [ 强调我的 ]

Appending ! 追加! to the type of a Swift declaration will give it optional type and annotate the declaration with an attribute stating that it may be implicitly unwrapped when used . 将Swift声明的类型赋予可选类型,并用一个属性声明声明声明该属性在使用时可能被隐式解开

Hence, it's entirely legal to use npill directly with the init?(_ text: String) initializer of Int , as it will be unwrapped (without any safety check for nil content!) on-the-fly upon use. 因此,直接将npillIntinit?(_ text: String)初始化程序一起使用是完全合法的,因为它将在使用时npill展开(无需对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!
    // ...
}

Generally you should avoid using the ! 通常您应该避免使用! annotation, however, unless you are entirely certain that the content of the resulting optional variable will never ever be nil . 但是,除非您完全确定生成的可选变量的内容永远不会为nil ,否则不能使用注解。

Leaving aside the cons of even using the ! 抛开甚至使用!的弊端! annotation: you may implement a safe version of the unsafe example above, by overriding the unsafe implicit unwrapping with safe explicit unwrapping techniques. 注:您可以通过使用安全的显式展开技术覆盖不安全的隐式展开来实现上述不安全示例的安全版本。 For a given optional variable declared using the ! 对于使用!声明的给定可选变量! annotation, we may still apply safe means to unwrap it, eg optional binding or using the nil coalescing operator. 注解,我们仍然可以使用安全的方法来解开它,例如,可选的绑定或使用nil合并运算符。 @appzYourLife has already showed one perfectly valid and safe way to handle the unwrapping and attempted type conversion of npill using optional binding, so I'll simply include another example using the nil coalescing operator instead: @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
}

The consensus of the examples above is that if we're even slightly uncertain whether npill can ever be nil or not, we need to treat it as if it was just an optional not type annotated with ! 上面示例的共识是,如果我们甚至不确定npill是否可以为nil ,我们需要将其视为只是一个可选的,未使用!注释的类型! (ie String? ); (即String? ); overriding the default unsafe unwrapping with safe means when working with the variable. 使用变量时,使用安全方法覆盖默认的不安全展开。 In such a case, why would we even want to use the ! 在这种情况下,我们为什么还要使用! typ annotation at all, as it only brings fragility/danger to our application? 根本没有类型注释,因为它只会给我们的应用程序带来脆弱性/危险?

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

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