什么时候用 Swift?

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)
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容