我需要简单解释一下为什么我使用 toInt()
将字符串转换为整数。
我什么时候需要使用 Int(variable)
而不是 variable.toInt()
最佳答案
swift 的 Int
没有接受 String
的构造函数.
任何时候你想转换 String
到Int
,您必须使用variable.toInt()
.
您只能使用 Int(variable)
如果variable
的类型在以下列表中:
-
Int
-
UInt8
-
Int8
-
UInt16
-
Int16
-
UInt32
-
Int32
-
UInt64
-
Int64
-
UInt
-
Float
-
Double
-
Float80
- 您编写自定义的任何其他类型
Int
extension
为并添加自定义init
为。
对于任何其他类型,您必须使用可用的 toInt()
方法(如果存在)或编写您自己的方法。
此列表中的内容与不在此列表中的内容之间的主要区别在于,在大多数情况下,Int
可以准确地代表此列表中的所有内容。 failable initializer对于这些类型中的任何一种都不是必需的。
尝试转换 "Hello World!"
时到Int
但是,我们应该返回什么? String
的 toInt()
返回 nil
因为String
的 toInt()
的返回类型是 Int?
(Int
可选)。在 init
中做同样的事情, init
必须是可失败的(我在答案底部发布了一个示例)。
但是,如果您要实现一个结构 Rational
为了表示有理分数,扩展 Int
可能是有意义的包含一个接受 Rational
的构造函数编号:
extension Int {
init(_ value: Rational) {
// your implementation
}
}
这是 Int
的可用构造函数列表(可以使用 Int(variable)
的情况:
/// A 64-bit signed integer value
/// type.
struct Int : SignedIntegerType {
/// Create an instance initialized to zero.
init()
/// Create an instance initialized to `value`.
init(_ value: Int)
/// Creates an integer from its big-endian representation, changing the
/// byte order if necessary.
init(bigEndian value: Int)
/// Creates an integer from its little-endian representation, changing the
/// byte order if necessary.
init(littleEndian value: Int)
init(_builtinIntegerLiteral value: Builtin.Int2048)
/// Create an instance initialized to `value`.
init(integerLiteral value: Int)
}
extension Int {
init(_ v: UInt8)
init(_ v: Int8)
init(_ v: UInt16)
init(_ v: Int16)
init(_ v: UInt32)
init(_ v: Int32)
init(_ v: UInt64)
/// Construct a `Int` having the same bitwise representation as
/// the least significant bits of the provided bit pattern.
///
/// No range or overflow checking occurs.
init(truncatingBitPattern: UInt64)
init(_ v: Int64)
/// Construct a `Int` having the same bitwise representation as
/// the least significant bits of the provided bit pattern.
///
/// No range or overflow checking occurs.
init(truncatingBitPattern: Int64)
init(_ v: UInt)
/// Construct a `Int` having the same memory representation as
/// the `UInt` `bitPattern`. No range or overflow checking
/// occurs, and the resulting `Int` may not have the same numeric
/// value as `bitPattern`--it is only guaranteed to use the same
/// pattern of bits.
init(bitPattern: UInt)
}
extension Int {
/// Construct an instance that approximates `other`.
init(_ other: Float)
/// Construct an instance that approximates `other`.
init(_ other: Double)
/// Construct an instance that approximates `other`.
init(_ other: Float80)
}
(您可以通过在 Swift 中的某处键入 Int(0)
,右键单击,然后单击“跳转到定义”来访问此列表。)
请注意,并非所有这些都是简单的 Int(variable)
, 其中一些必须像 Int(littleEndian:variable)
这样使用例如。
您可以使用的唯一方法 Int(variable)
其中 variable
是 String
将是将您自己的扩展名添加到 Int
:
extension Int {
init?(_ s: String) {
if let i = s.ToInt() {
init(i)
} else {
init(0)
return nil
}
}
}
但我建议坚持使用 variable.ToInt()
.
关于Int() 和 toInt() 之间的 Swift 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29183259/