723_advances_in_foundation

0x1 有序集合diff

//bird [b,i,r,d]
//bear [b,e,a,r]
let diff = bird.difference(from:bear) 
let newBird = bear.applying(diff) //[b,i,r,d]

0x2数据连续性

struct Data使用protocol ContiguousBytes 做了内存数据连续性优化

public protocol ContiguousBytes {
func withUnsafeBytes(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R
}

对于其他类型使用了下面的某个协议做了优化

public protocol DataProtocol: RandomAccessCollection where Element == UInt8, ... { }
public protocol MutableDataProtocol : DataProtocol, MutableCollection, RangeReplaceableCollection { }

已适配protocol的类型 Data [UInt8] DispatchData

0x3数据压缩

let compressed = try data.compressed(using: .lzfse)
public enum CompressionAlgorithm : Int { case lzfse
    case lz4
    case lzma
    case zlib
}

0x4单位

UnitDuration

  • Added milliseconds, microseconds, nanoseconds, and picoseconds

UnitFrequency

  • Added framesPerSecond

UnitInformationStorage

  • bits, bytes, nibbles for common usage
  • SI- and binary-prefixed units (kilo, kibi, ... yotta, yobi) Format with MeasurementFormatter - and ByteCountFormatter

0x5日期展示

let formatter = RelativeDateTimeFormatter()
let dateString = formatter.localizedString(for: aDate, relativeTo: now)
// en_US:  "2 weeks ago"
// es_ES:  "hace 2 semanas"
// zh_TW:  "2 週前"
let string = ListFormatter.localizedString(byJoining: ["
// en_US: ", , and "
// es_ES: ",  y "
// zh_TW: ",  和 "
image.png
let listFormatter = ListFormatter() let dateFormatter = DateFormatter()
listFormatter.itemFormatter = dateFormatter let string = listFormatter.string(from: dates)
// en_US: "8/15/19, 9/13/19, and 2/1/20" 
// es_ES: "15/8/19, 13/9/19 y 1/2/20”

0x6 Operation Queue

  • 支持addBarrierBlock
queue.addBarrierBlock { 
    save()
}
  • 进度报告
let queue = OperationQueue() 
queue.progress.totalUnitCount = 3
queue.addOperation { 
    task1()                                 // Finished task: 1 / 3
} 
queue.addOperation {
    task2()                                 // Finished task: 2 / 3
}
queue.addOperation { 
    task3()                                 // Finished task: 3 / 3
}

0x7 USB 和 SMB

  • 选择存储位置时使用FileManager.SearchPathDirectory.itemReplacementDirectory
  • 对于可能挂掉的卷使用Data.ReadingOptions.mappedIfSafe 来安全存储

0x8 swift5 API简化

// Swift 4
var nameNSString: NSString?
if scanner.scanUpToCharacters(from: .newlines, into: &nameNSString) {
    let name = nameNSString! as String 
}
 // Swift 5.1
let nameString = scanner.scanUpToCharacters(from: .newlines) 
let matchedString = scanner.scanString(string: "hi, $")
  • FileHandle 支持 try
let fileHandle = FileHandle()
let data = try fileHandle.readToEnd()
extension FileHandle {
   public func write(contentsOf data: T) throws
}

你可能感兴趣的:(723_advances_in_foundation)