1.我们先来建立一个protocol,他的功能就是让实现类实现一个SegueIdentifier别名,这个SegueIdentifier必需为RawRepresentable类型,在后边我们就会用 protocol SegueHandlerType { associatedtype SegueIdentifier: RawRepresentable } 2.我们要对上边的protocol扩展,并且实现
增加@AppStorage支持的数据类型 除了上述的类型外,@AppStorage还支持符合RawRepresentable协议且RawValue为Int或String的数据类型。 通过增加RawRepresentable协议的支持,我们可以在@AppStorage中读取存储原本并不支持的数据类型。 下面的代码添加了对Date类型的支持: extension Date:RawRepresentable{ public typealias RawValue = String public } } 使用起来和直接支持的类型完全一致: @AppStorage("date") var date = Date() 下面的代码添加了对Array的支持: extension Array: RawRepresentable 我并不打算将配置数据汇总到一个结构体中并通过支持RawRepresentable协议统一保存。
讨论RawRepresentable 和 LosslessStringConvertible 的区别[9]LosslessStringConvertible 改进了 CustomStringConvertible 从语义上讲,LosslessStringConvertible 意味着它可以表示为字符串(例如整数),而 RawRepresentable 意味着它在底层是一个字符串(例如原始类型为 String 的枚举 Objective-C 代码库迁移到 Swift: https://forums.swift.org/t/migrating-an-objective-c-codebase-to-swift/61592 [9]RawRepresentable 和 LosslessStringConvertible 的区别: https://forums.swift.org/t/difference-between-rawrepresentable-string-and-losslessstringconvertible
RawRepresentable protocol RangeReplaceableCollection<Element>: Collectionpublic protocol Identifiable<ID>public protocol RawRepresentable
} 如果是typedef typedef enum{ Num1, Num2, }OCNum; 直接查看转换过后的文件.h public struct OCnum :Equatable,RawRepresentable
return String(self.rawValue) } } } 注意 枚举类型可以Int String等基本类型的值,对象是不可以的,官方说必须是实现RawRepresentable
lessThanOrEqual case equal case greaterThanOrEqual } 约束的优先级 public struct UILayoutPriority : RawRepresentable
之前只有遵循rawRepresentable的enum才能使用Codable。
指定的名字是作为别名存在,可以互换使用: /// Describes the priority of a task. struct TaskPriority: Codable, Comparable, RawRepresentable