[swift-evolution] [swift-evolution-announce] [Returned for revision] SE-0089: Renaming String.init<T>(_: T)

Vladimir.S svabox at gmail.com
Mon May 30 17:04:38 CDT 2016


Thank you, Brent. But for me you just described a serialization to/from 
string ;)

So, using your example, if I have

struct A: CustomStringConvertible {
     var a = 0, b = 0
     var description: String { return "a:\(a) b:\(b)" }
}

and I want to use it in your code. Will I be able to do this?
For example, I'm ok to give it 'lossless' representation as "\(a)/\(b)" 
(i.e. 1/2 for example) and provide init() for string of such format.

I.e. it seems like I just should create extension and conform to 
LosslessStringConvertible, but as I understand I can't, as I need not only 
introduce an init(:String), but modify `description` property ?
I.e. assume you have no rights or don't want to modify the A type itself.

This is why I don't understand why we should have the same .description for 
this LosslessStringConvertible(i.e. if it will be .loslessDescription - no 
problems).
Most likely I don't understand something.

Also there is a question regarding your example: what to do with Double 
type? We can have some configuration items of Double type, but how to use 
this LosslessStringConvertible here?

On 31.05.2016 0:22, Brent Royal-Gordon wrote:
>> I can't understand this. For me ValuePreservingStringConvertible usually will be different than CustomStringConvertible. Can't I want to have some string view of my struct to present data(also in UI) *and* value preserving string value for the same struct?
>> So my .description will show something like "12.345-6.78" and value preserving string will contain something like "19083749347923847293487293483" to encode the data of the struct. No?
>
> Rather than thinking of LosslessStringConvertible as a protocol for serializing data into a string, think of it as a protocol for those cases where the human-readable description is also parseable and can be used to completely recreate the instance. It's something you would use for things like command-line arguments, environment variables, interactive command-line programs, and configuration files that you expect humans to read and write by hand.
>
> 	func prompt<T: LosslessStringConvertible>(for field: String, of type: T.Type) -> T {
> 		while true {
> 			print("What's your \(field)?")
> 			
> 			let line = readline()
> 			
> 			if	!line.isEmpty
> 				let value = T(line) {		// how the hell do you indent this stupid syntax?
> 				return value
> 			}
> 		}
> 	}
> 	
> 	let name = prompt(for: "name", of: String)
> 	let age = prompt(for: "age", of: Int)
> 		
> 	let answer = age < 13 ? " not" : ""
> 	print("\(name), you are\(answer) too old to have a favorite color.")
>
> In other words, write the `description` first, and then decide if you can write a good `init(_ description:)` to match it.
>


More information about the swift-evolution mailing list