Change what print(Object) displays in Swift 2.0 - swift

I am trying to make my class Digit display the num variable whenever print is called on that object, in Swift 2.0. I thought this might be done with a description variable, but no luck.
class Digit {
var num: Int
var x: Int
var y: Int
var box: Int
var hintList: [Int] = []
var guess: Bool = false
var description: String {
let string = String(num)
return string
}
}

It isn't enough to just add a description variable. You need to also state that your class conforms to CustomStringConvertible (formerly known as Printable in earlier Swift versions).
If you command click the print function, you find the following description.
Writes the textual representation of value, and an optional newline,
into the standard output.
The textual representation is obtained from the value using its protocol
conformances, in the following order of preference: Streamable,
CustomStringConvertible, CustomDebugStringConvertible. If none of
these conformances are found, a default text representation is constructed
in an implementation-defined way, based on the type kind and structure.
The part of which that matters here being that objects passed to print are not checked for whether or not they have a description method, but instead checked for things like whether or not the conform to protocols like CustomStringConvertible which offer data to be printed.
That being said, all you need to do in this case is specify that your class conforms to CustomStringConvertible since you've already added a description variable. If you hadn't already added this, the compiler would complain because this protocol requires that the description variable be implemented.
class Digit: CustomStringConvertible {
var num: Int
var x: Int
var y: Int
var box: Int
var hintList: [Int] = []
var guess: Bool = false
var description: String {
let string = String(num)
return string
}
}

Related

Is it possible to change Swift String Interpolation for the String typealias?

I have a lot of DTOs in my app which log some field. That field should not be logged because the data is kind of sensitive.
The model looks like this:
typealias HiddenFieldType = String
struct DTO1 {
var field1_1: String
var fieldToHide: HiddenFieldType
var field1_2: String
var field1_3: String
}
struct DTO2 {
var field2_1: String
var field2_2: String
var fieldToHide: HiddenFieldType
var field2_3: String
}
the code which outputs the data is like this (actually it's os_log in a real app):
func test() {
let dto1 = DTO1(field1_1: "1_1", fieldToHide: "super-secret-1", field1_2: "1_2", field1_3: "1_3")
let dto2 = DTO2(field2_1: "2_1", field2_2: "2_2", fieldToHide: "super-secret-2", field2_3: "2_3")
print("Test1: dto1=\(dto1) dto2=\(dto2)")
}
Approach #1
It seems the field can be hidden in DTO1 with such code:
extension String.StringInterpolation {
mutating func appendInterpolation(_ value: DTO1) {
appendInterpolation("field1_1: \(value.field1_1), fieldToHide: 🤷‍♀️, field1_2: \(value.field1_2), field1_3: \(value.field1_3)")
}
}
However, the solution is neither scalable nor maintainable:
the same extension should be added for each DTO
each field should be included into appendInterpolation - a lot of boilerplate
if a new field is added to some DTO, we may forget to update appendInterpolation etc
Approach #2
I tried to add interpolation for HiddenFieldType (assuming it's a type, just like DTO1...):
extension String.StringInterpolation {
mutating func appendInterpolation(_ value: HiddenFieldType) {
appendInterpolation("🤷‍♀️")
}
}
But this solution doesn't work at all:
the compiler says "Function call causes an infinite recursion"
and it actually causes an infinite recursion
when changing appendInterpolation to appendLiteral, there's no recursion, but "super-secret-1" is not hidden
Approach #3
I tried overriding DefaultStringInterpolation, conforming to ExpressibleByStringLiteral/ExpressibleByStringInterpolation, but it doesn't work: the compiler says that HiddenFieldType is String, and Conformance of 'String' to protocol 'ExpressibleByStringLiteral' was already stated in the type's module 'Swift'
The only approach I can imagine is changing typealias HiddenFieldType = String to struct HiddenFieldType { let value: String }, so the HiddenFieldType becomes a "real" type.
Approach #4
Then such code doesn't cause an infinite recursion anymore, but doesn't works either (the value is unhidden)
struct HiddenFieldType {
let value: String
}
extension String.StringInterpolation {
mutating func appendInterpolation(_ value: HiddenFieldType) {
appendInterpolation("🤷‍♀️")
}
}
Approach #5
This code finally works:
struct HiddenFieldType {
let value: String
}
extension HiddenFieldType: CustomStringConvertible {
var description: String {
"🤷‍♀️"
}
}
As I can't imagine any better, for now I'd use this approach, but it also has some slight scalability issues, as I must update each DTO's initializing point:
from
let dto1 = DTO1(field1_1: "1_1", fieldToHide: "super-secret-1", field1_2: "1_2", field1_3: "1_3")
to
let dto1 = DTO1(field1_1: "1_1", fieldToHide: .init(value: "super-secret-1"), field1_2: "1_2", field1_3: "1_3")
and I hoped to only add some extension in the file which contains typealias HiddenFieldType = String, and not to update the entire code.
The questions
Is it possible to hide the value of HiddenFieldType without changing it from typealias to struct, and without updating each DTO?
Is there any better approach than 5?
Thanks in advance
Is it possible to hide the value of HiddenFieldType without changing it from typealias to struct
I think you're attempting to use the wrong tool for the job here. A typealias is just a name change, and it sounds like you want something that acts fundamentally different than a String (i.e. one gets printed when passed into an os_log call and one doesn't). You won't be able to write logic that treats a String different from its typealias; the compiler doesn't differentiate between them.
Is it possible to make your DTOs classes instead of structs? (EDIT: see below, you can keep them as structs and just use a protocol extension) If so, you could use reflection on a superclass to accomplish this without having to manually specify the description for every different DTO.
struct HiddenFieldType {
let value: String
}
open class DTO: CustomStringConvertible {
public var description: String {
Mirror(reflecting: self).children.compactMap { $0.value as? String }.joined(separator: "\n")
}
}
final class DTO1: DTO {
let field1_1: String
let field1_2: String
let fieldToHide: HiddenFieldType
init(field1_1: String, field1_2: String, fieldToHide: HiddenFieldType) {
self. field1_1 = field1_1
self. field1_2 = field1_2
self. fieldToHide = fieldToHide
}
}
Note that I'm including all Strings in the description but, if you have types other than String and HiddenFieldType that you want to log, you could always just filter out the HiddenFieldTypes specifically.
Personally, I'd be hesitant to rely on reflection for any critical code but other people have more tolerance for it so its a judgement call.
EDIT:
You don't need to use inheritance to accomplish this. Instead of a superclass, DTO should be a protocol that conforms to CustomStringConvertible:
protocol DTO: CustomStringConvertible {}
extension DTO {
public var description: String {
Mirror(reflecting: self).children.compactMap { $0.value as? String }.joined(separator: "\n")
}
}

Values of structs changing when appending to array with protocol type

I have a protocol, and some structs that conform to it, basically in the format shown below. I'm facing an issue where if I append different structs to an array of type [Protocol], the values of the structs are changing in a weird way. However, if I change the type of the array to [Struct1] or [Struct2], and only append the appropriate types, there's no problem.
protocol Protocol {
var id: String { get set }
var name: String { get set }
}
struct Struct1: Protocol {
var id: String = "1"
var name: String = "Struct1"
var uniqueProperty1: String = "uniqueProperty1"
}
struct Struct2: Protocol {
var id: String = "2"
var name: String = "Struct2"
var uniqueProperty2: String = "uniqueProperty2"
}
var structs: [Protocol] = []
let struct1 = Struct1()
let struct2 = Struct2()
structs.append(struct1)
structs.append(struct2)
And I should add, the above code works as expected. It's my project that has a protocol and some structs however that are behaving strangely. What could be causing this issue?
I discovered that if you look at the value of an element within an array of type [Protocol] in the Variables View within the Debug Area, it's possible that it won't reflect that element's actual values.
Here's an example:
You can see that itemsList in cards[2] is nil, but when I print out the same value in the Debugger Output of the Console, it's not nil (has a length of 4):
(lldb) po (cards[2] as? RBListCard)?.itemsList?.count
▿ Optional<Int>
- some : 4
I guess the moral of the story is don't trust the values that show up within the Variables View.

Literal Convertibles in Swift

I want to know how Literal Convertibles work in Swift. The little I know is that the fact that, in var myInteger = 5, myInteger magically becomes an Int is because Int adopts a protocol, ExpressibleByIntegerLiteral and we don't have to do var myInteger = Int(5). Similarly String, Array, Dictionary etc all conform to some Literal protocols.
My Question is
Am I right in my little understanding of Literal Convertibles?
How can we implement these in our own types. For example
class Employee {
var name: String
var salary: Int
// rest of class functionality ...
}
How can I implement Literal Protocols to do var employee :Employee = "John Doe" which will automatically assign "John Doe" to employee's name property.
You are partially correct in your understanding of the various ExpressibleBy...Literal protocols. When the Swift compiler parses your source code into an Abstract Syntax Tree, it already identified what literal represents what data type: 5 is a literal of type Int, ["name": "John"] is a literal of type Dictionary, etc. Apple makes the base type conform to these protocols for the sake of completeness.
You can adopt these protocols to give your class an opportunity to be initialized from a compile-time constant. But the use case is pretty narrow and I don't see how it applies to your particular situation.
For example, if you want to make your class conform to ExpressibleByStringLiteral, add an initializer to set all your properties from a String:
class Employee: ExpressibleByStringLiteral {
typealias StringLiteralType = String
var name: String
var salary: Int
required init(stringLiteral value: StringLiteralType) {
let components = value.components(separatedBy: "|")
self.name = components[0]
self.salary = Int(components[1])!
}
}
Then you can init your class like this:
let employee1: Employee = "John Smith|50000"
But if you dream about about writing something like this, it's not allowed:
let str = "Jane Doe|60000"
let employee2: Employee = str // error
And if you pass in the wrong data type for salary, it will be a run time error instead of a compile-time error:
let employee3: Employee = "Michael Davis|x" // you won't know this until you run the app
TL, DR: it is a very bad idea to abuse these ExpressibleBy...Literal types.
This can be a scenario to work with Convertibles in custom types.
struct Employee : ExpressibleByStringLiteral {
var name: String = ""
init() {}
init(stringLiteral name: String) {
self.name = name
}
}
func reportName(_ employee: Employee) {
print("Name of employee is \(employee.name)")
}
reportName("John Doe") //Name of employee is John Doe

Protocol function implementation without actually conforming to a protocol

I am a beginner Swift learner and I have a question about protocols. I have followed a tutorial that teaches you about linked lists, which is as follows:
Node:
class LinkedListNode<Key> {
let key: Key
var next: LinkedListNode?
weak var previous: LinkedListNode?
init (key: Key) {
self.key = key
}
}
And the linked list:
class LinkedList<Element>: CustomStringConvertible {
typealias Node = LinkedListNode<Element>
private var head: Node?
// irrelevant code removed here
var description: String {
var output = "["
var node = head
while node != nil {
output += "\(node!.key)"
node = node!.next
if node != nil { output += ", " }
}
return output + "]"
}
}
The var description: String implementation simply lets you to print each elements in the linked list.
So far, I understand the structure of the linked list, my problem isn't about the linked list actually. What I don't understand is the protocol CustomStringConvertible. Why would it be wrong if I have only the var description: String implementation without conforming to the protocol? I mean, this protocol just simply say "Hey, you need to implement var description: String because you are conformed to me, but why can't we just implement var description: String without conforming to the protocol?
Is it because in the background, there is a function or some sort that takes in a type CustomStringConvertible and run it through some code and voila! text appears.
Why can't we just implement var description: String without conforming to the protocol?
Compare:
class Foo {
var description: String { return "my awesome description" }
}
let foo = Foo()
print("\(foo)") // return "stackoverflow.Foo" (myBundleName.Foo)
and
class Foo: CustomStringConvertible {
var description: String { return "my awesome description" }
}
let foo = Foo()
print("\(foo)") // return "my awesome description"
When you use CustomStringConvertible, you warrant that this class have the variable description, then, you can call it, without knowing the others details of implementation.
Another example:
(someObject as? CustomStringConvertible).description
I don't know the type of someObject, but, if it subscriber the CustomStringConvertible, then, I can call description.
You must conform to CustomStringConvertible if you want string interpolation to use your description property.
You use string interpolation in Swift like this:
"Here's my linked list: \(linkedList)"
The compiler basically turns that into this:
String(stringInterpolation:
String(stringInterpolationSegment: "Here's my linked list: "),
String(stringInterpolationSegment: linkedList),
String(stringInterpolationSegment: ""))
There's a generic version of String(stringInterpolationSegment:) defined like this:
public init<T>(stringInterpolationSegment expr: T) {
self = String(describing: expr)
}
String(describing: ) is defined like this:
public init<Subject>(describing instance: Subject) {
self.init()
_print_unlocked(instance, &self)
}
_print_unlocked is defined like this:
internal func _print_unlocked<T, TargetStream : TextOutputStream>(
_ value: T, _ target: inout TargetStream
) {
// Optional has no representation suitable for display; therefore,
// values of optional type should be printed as a debug
// string. Check for Optional first, before checking protocol
// conformance below, because an Optional value is convertible to a
// protocol if its wrapped type conforms to that protocol.
if _isOptional(type(of: value)) {
let debugPrintable = value as! CustomDebugStringConvertible
debugPrintable.debugDescription.write(to: &target)
return
}
if case let streamableObject as TextOutputStreamable = value {
streamableObject.write(to: &target)
return
}
if case let printableObject as CustomStringConvertible = value {
printableObject.description.write(to: &target)
return
}
if case let debugPrintableObject as CustomDebugStringConvertible = value {
debugPrintableObject.debugDescription.write(to: &target)
return
}
let mirror = Mirror(reflecting: value)
_adHocPrint_unlocked(value, mirror, &target, isDebugPrint: false)
}
Notice that _print_unlocked only calls the object's description method if the object conforms to CustomStringConvertible.
If your object doesn't conform to CustomStringConvertible or one of the other protocols used in _print_unlocked, then _print_unlocked creates a Mirror for your object, which ends up just printing the object's type (e.g. MyProject.LinkedList) and nothing else.
CustomStringConvertible allows you to do a print(linkedListInstance) that will print to the console whatever is returned by the description setter.
You can find more information about this protocol here: https://developer.apple.com/reference/swift/customstringconvertible

Why Are My Default Property Values Still Showing as Parameters in Init()?

I have a protocol that describes a marine water parameter that needs tested:
protocol Parameter {
var name: String { get }
var unit: Unit { get }
var value: Double { get }
}
I have a struct, Calcium, that conforms to Parameter:
struct Calcium: Parameter {
var name: String = "Calcium"
var unit: Unit = UnitDispersion.partsPerMillion
var value: Double
}
Since the name and unit parameters of Calcium have default values, why do I need to provide them in the init method? Shouldn't I only need to provide a value for value?
I am trying to understand protocol-oriented-programming and would really appreciate a little guidance here.
This has nothing whatever to do with protocols.
You do not have to provide an initializer for anything but the value. But you have not provided any initializer. Therefore the only initializer you have is the one provided automatically, and that initializer is the memberwise initializer which wants parameters for all your properties.
If you don't like that, write an initializer yourself:
struct Calcium: Parameter {
var name: String = "Calcium"
var unit: Unit = UnitDispersion.partsPerMillion
var value: Double
init(value:Double) {self.value = value}
}
Now it is legal to say:
let c = Calcium(value:2)