Swift 中 Hashable 一定是 Equatable,因为前者继承了后者。 在Swift 4中,若遵循Equatable协议的时候,我们必须实现Equatable协议的==方法, Equatable协议如下:
1 2 3 4 5 6 7 8 9 10 11 12
public protocol Equatable {
/// Returns a Boolean value indicating whether two values are equal. /// /// Equality is the inverse of inequality. For any values `a` and `b`, /// `a == b` implies that `a != b` is `false`. /// /// - Parameters: /// - lhs: A value to compare. /// - rhs: Another value to compare. public static func == (lhs: Self, rhs: Self) -> Bool }
在Swift4.0中, 必须实现Equatable协议的方法
1 2 3 4 5 6 7 8 9
struct Name: Equatable { var name1 = "name1" var name2 = "name2"
struct Student: Codable, Hashable { let firstName: String let averageGrade: Int }
let cosmin = Student(firstName: "Cosmin", averageGrade: 10) let george = Student(firstName: "George", averageGrade: 9) let encoder = JSONEncoder()
// Encode an Array of students let students = [cosmin, george] do { try encoder.encode(students) } catch { print("Failed encoding students array: \(error)") }
// Encode a Dictionary with student values let studentsDictionary = ["Cosmin": cosmin, "George": george] do { try encoder.encode(studentsDictionary) } catch { print("Failed encoding students dictionary: \(error)") }
// Encode a Set of students let studentsSet: Set = [cosmin, george] do { try encoder.encode(studentsSet) } catch { print("Failed encoding students set: \(error)") }
// Encode an Optional Student let optionalStudent: Student? = cosmin do { try encoder.encode(optionalStudent) } catch { print("Failed encoding optional student: \(error)") }
// Swift 4 protocol Tune { unowned var key: Key { get set } weak var pitch: Pitch? { get set } } // Swift 4.1 protocol Tune { var key: Key { get set } var pitch: Pitch? { get set } }
UnsafeMutableBufferPointer的改变
1 2 3 4 5 6 7 8 9
//Swift4.0 let buffer = UnsafeMutableBufferPointer<Int>(start: UnsafeMutablePointer<Int>.allocate(capacity: 10), count: 10) let mutableBuffer = UnsafeMutableBufferPointer(start: UnsafeMutablePointer(mutating: buffer.baseAddress), count: buffer.count)
//Swift4.1 let buffer = UnsafeMutableBufferPointer<Int>.allocate(capacity: 10) let mutableBuffer = UnsafeMutableBufferPointer(mutating: UnsafeBufferPointer(buffer))