structPersonStruct{ enumGender: Int{ case male case female } var name: String? var gender: Gender? privatevar age: Int? init(name: String, gender: Gender, age: Int) { self.name = name self.gender = gender self.age = age } }
extensionPersonStruct{ funcgetPersonAge() -> Int? { return age } mutatingfuncsetPersonAge(_ age: Int?) { self.age = age } }
classTestClassAndProtocol{ // in swift3 var oldDelegate: SomeClass? var oldDelegate_P: SomeProtocol? { if oldDelegate == nil { returnnil } let delegate_P = oldDelegate as? SomeProtocol assert(delegate_P != nil, "oldDelegate must is nil or a SomeClass's object and conforming to SomeProtocol") return delegate_P } // in swift4 var delegate: (SomeClass & SomeProtocol)? }
let multiLineString = """ // Some Code extension String : StringProtocol, RangeReplaceableCollection { /// A type that represents the number of steps between two `String.Index` /// values, where one value is reachable from the other. /// /// In Swift, *reachability* refers to the ability to produce one value from /// the other through zero or more applications of `index(after:)`. public typealias IndexDistance = String.CharacterView.IndexDistance /// A sequence that represents a contiguous subrange of the collection's /// elements. public typealias SubSequence = Substring ..... } =========== Get Value: \(str) =========== """ print(multiLineString)
/// A type that can encode itself to an external representation. publicprotocolEncodable{
/// Encodes this value into the given encoder. /// /// If the value fails to encode anything, `encoder` will encode an empty /// keyed container in its place. /// /// This function throws an error if any values are invalid for the given /// encoder's format. /// /// - Parameter encoder: The encoder to write data to. publicfuncencode(to encoder: Encoder)throws }
/// A type that can decode itself from an external representation. publicprotocolDecodable{
/// Creates a new instance by decoding from the given decoder. /// /// This initializer throws an error if reading from the decoder fails, or /// if the data read is corrupted or otherwise invalid. /// /// - Parameter decoder: The decoder to read data from. publicinit(from decoder: Decoder) throws }
/// A type that can convert itself into and out of an external representation. publictypealiasCodable = Decodable & Encodable
classHuman: Codable{ var name: String var age: Int var dogs: [Dog] var birthday: Date enumCodingKeys: String, CodingKey{ case name = "userName" case age = "userAge" case dogs case birthday } // 解析 json classfuncdecode(forResourceresource: String) -> Human? { guardlet humanJsonData = try? getJSONData(forResource: resource, ofType: "json"), let human = try? decoder.decode(Human.self, from: humanJsonData) else { print("Get JSON Data or Decoder Error") returnnil } return human } // 序列化为json funcencode()throws -> Data { returntry encoder.encode(self) } }
// 示例 iflet human = Human.decode(forResource: "human") { print(human.name) print(human.age) print(human.birthday) for dog in (human.dogs) { print("\(dog.name) \t \(dog.age) \t \(dog.gender) \t \(dog.nikeName ?? "nil")") } iflet data = try? human.encode() { print(String(data: data, encoding: .utf8) ?? "Error") } }
/// The strategy to use for encoding `Date` values. publicenumDateEncodingStrategy{ case deferredToDate /// Defer to `Date` for choosing an encoding. This is the default strategy. case secondsSince1970 /// Encode the `Date` as a UNIX timestamp (as a JSON number). case millisecondsSince1970 /// Encode the `Date` as UNIX millisecond timestamp (as a JSON number). case iso8601 /// Encode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). case formatted(DateFormatter) /// Encode the `Date` as a string formatted by the given formatter. case custom((Date, Encoder) throws -> Swift.Void) /// Encode the `Date` as a custom value encoded by the given closure. /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. }
decoder.dateDecodingStrategy
JSONDecoder.DateDecodingStrategy
1 2 3 4 5 6 7 8 9
/// The strategy to use for decoding `Date` values. publicenumDateDecodingStrategy{ case deferredToDate /// Defer to `Date` for decoding. This is the default strategy. case secondsSince1970 /// Decode the `Date` as a UNIX timestamp from a JSON number. case millisecondsSince1970 /// Decode the `Date` as UNIX millisecond timestamp from a JSON number. case iso8601 /// Decode the `Date` as an ISO-8601-formatted string (in RFC 3339 format). case formatted(DateFormatter) /// Decode the `Date` as a string parsed by the given formatter. case custom((Decoder) throws -> Date) /// Decode the `Date` as a custom value decoded by the given closure. }
Data
encoder.dataEncodingStrategy
JSONEncoder.DataEncodingStrategy
1 2 3 4 5 6 7
/// The strategy to use for encoding `Data` values. publicenumDataEncodingStrategy{ case deferredToData /// Defer to `Data` for choosing an encoding. case base64 /// Encoded the `Data` as a Base64-encoded string. This is the default strategy. case custom((Data, Encoder) throws -> Swift.Void) /// Encode the `Data` as a custom value encoded by the given closure. /// If the closure fails to encode a value into the given encoder, the encoder will encode an empty automatic container in its place. }
decoder.dataDecodingStrategy
JSONDecoder.DataDecodingStrategy
1 2 3 4 5 6
/// The strategy to use for decoding `Data` values. publicenumDataDecodingStrategy{ case deferredToData /// Defer to `Data` for decoding. case base64 /// Decode the `Data` from a Base64-encoded string. This is the default strategy. case custom((Decoder) throws -> Data) /// Decode the `Data` as a custom value decoded by the given closure. }
Float
encoder.nonConformingFloatEncodingStrategy
JSONEncoder.NonConformingFloatEncodingStrategy
1 2 3 4 5 6 7
/// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). publicenumNonConformingFloatEncodingStrategy{ case `throw` /// Throw upon encountering non-conforming values. This is the default strategy. case convertToString(positiveInfinity: String, negativeInfinity: String, nan: String) /// Encode the values using the given representation strings. }
decoder.nonConformingFloatDecodingStrategy
JSONDecoder.NonConformingFloatDecodingStrategy
1 2 3 4 5 6 7
/// The strategy to use for non-JSON-conforming floating-point values (IEEE 754 infinity and NaN). publicenumNonConformingFloatDecodingStrategy{ case `throw` /// Throw upon encountering non-conforming values. This is the default strategy. case convertFromString(positiveInfinity: String, negativeInfinity: String, nan: String) /// Decode the values from the given representation strings. }