1. 当你需要使用 Swift string 的方法的时候
在 Objective-C 中,所有的 Swift string 都被转化成了 NSString 对象。
用 Swift,可以轻易的将一个 Int 型转化为任意进制的 Swift string。而用 Objective-C,却无法调用 Swift string 的这个初始化方法。
let initialBits: UInt8 = 0b00001111
let invertedBits = ~initialBits // equals 11110000
let stringOfInvertedBits = String(invertedBits, radix: 2) // convert to string in binary
print(stringOfInvertedBits) // 11110000
2. 当你需要使用泛型的时候
extension String {
/// Create an instance representing `v` in base 10.
public init<T : _SignedIntegerType>(_ v: T)
/// Create an instance representing `v` in base 10.
public init<T : UnsignedIntegerType>(_ v: T)
/// Create an instance representing `v` in the given `radix` (base).
///
/// Numerals greater than 9 are represented as roman letters,
/// starting with `a` if `uppercase` is `false` or `A` otherwise.
public init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
/// Create an instance representing `v` in the given `radix` (base).
///
/// Numerals greater than 9 are represented as roman letters,
/// starting with `a` if `uppercase` is `false` or `A` otherwise.
public init<T : UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool = default)
}
网友评论