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

Brent Royal-Gordon brent at architechies.com
Mon May 30 16:22:33 CDT 2016


> 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.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-evolution mailing list