https://developer.apple.com/documentation/swift/expressiblebystringliteral
Overview
The String and StaticString types conform to the ExpressibleByStringLiteralprotocol. You can initialize a variable or constant of either of these types using a string literal of any length.
Conforming to ExpressibleByStringLiteral
To add ExpressibleByStringLiteral conformance to your custom type, implement the required initializer.
https://developer.apple.com/documentation/swift/customstringconvertible
Overview
Types that conform to the CustomStringConvertible protocol can provide their own representation to be used when converting an instance to a string. The String(describing:) initializer is the preferred way to convert an instance of any type to a string. If the passed instance conforms to CustomStringConvertible, the String(describing:) initializer and the print(_:) function use the instance’s custom description property.
Accessing a type’s description property directly or using CustomStringConvertible as a generic constraint is discouraged.
Conforming to the CustomStringConvertible Protocol
Add CustomStringConvertible conformance to your custom types by defining a description property.
For example, this custom Point struct uses the default representation supplied by the standard library:
Example
enum CompassPoint {
case north
case south
case custom(String)
}
extension CompassPoint: ExpressibleByStringLiteral {
init(stringLiteral value: String) {
switch value {
case "north":
self = .north
case "south":
self = .south
default:
self = .custom(value)
}
}
}
extension CompassPoint: CustomStringConvertible {
public var description: String {
switch self {
case .north:
return "north"
case .south:
return "south"
case .custom(let type):
return type
}
}
}
'iOS > Swift' 카테고리의 다른 글
[Swift 5.2] Subscripts - Apple Documentation (0) | 2020.03.05 |
---|---|
[Swift 5.2] Methods - Apple Documentation (0) | 2020.03.05 |
[Swift4.1] map, flapMap, compactMap (0) | 2019.12.11 |
[Swift 5.2] Properties - Apple Documentation (0) | 2019.12.08 |
[Swift5.1] Overview (0) | 2019.12.04 |