我需要简单的解释为什么toInt()
将字符串转换为整数。
我什么时候需要使用Int(variable)
代替variable.toInt()
Swift的Int
没有接受的构造函数String
。
每当您要将a转换String
为an时Int
,都必须使用variable.toInt()
。
您只能使用Int(variable)
如果variable
的类型是以下列表:
Int
UInt8
Int8
UInt16
Int16
UInt32
Int32
UInt64
Int64
UInt
Float
Double
Float80
Int
extension
为其编写自定义并为其添加自定义的任何其他类型init
。对于任何其他类型,必须使用可用的toInt()
方法(如果存在),或者编写自己的方法。
此列表中的内容与未列表中的内容之间的主要区别在于,在大多数情况下,它们Int
可以准确地表示该列表中的所有内容。对于这些类型中的任何一种,都不需要使用失败的初始化程序。
当尝试转换"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)
}
(您可以通过Int(0)
在Swift中的某个位置键入内容,右键单击并单击“跳转到定义”来获得此列表。)
请注意,并非所有这些都是简单的Int(variable)
,Int(littleEndian:variable)
例如,必须使用其中的一些。
您可以Int(variable)
在where使用的唯一方法variable
是String
将您自己的扩展名添加到Int
:
extension Int {
init?(_ s: String) {
if let i = s.ToInt() {
init(i)
} else {
init(0)
return nil
}
}
}
但我建议您坚持使用variable.ToInt()
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句