The compiler is unable to type-check this expression in reasonable time... String [edit] addition with an Int in the mix (solved)

Hello,

I've heard of the error "The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions" before, but never seen it myself.

I was surprised to find it with this, seemingly simple code:

public struct HikVisionCamera: Codable {
	var localIPAddress: String
	var username: String
	var password: String
	var channel: Int
	
	func srcURL() -> String {
		return "http://" + username + ":" + password + "@" + localIPAddress + "/ISAPI/Streaming/channels/" + channel + "/picture"
	}
}

Is this a bug? Do I really need to break this down into sub-chunks?

[Edit]

Hmmm, I see that I have to create a String from the Int as String won't interpolate the Int directly - the following code does work.

Should my previous code confuse the type-checker that much?

Thanks


public struct HikVisionCamera: Codable {
	var localIPAddress: String
	var username: String
	var password: String
	var channel: Int
	
	func srcURL() -> String {
		let userPass = username + ":" + password
		let path = "/ISAPI/Streaming/channels/" + String(channel) + "/picture"
		let src = "http://" + userPass + "@" + localIPAddress + path
		return src
	}
}

[edit 2] - just to be clear - the breaking-down didn't solve the problem, but it helped me find where the issue was.

Issue here is the use of +. Given the number of overloads available for that operator the compiler has real trouble inferring large expressions. It would be simplest to just use string interpolation instead. return "http://\(username):\(password)@\(localIPAddress)/ISAPI/Streaming/channels/\(channel)/picture" However, you probably want to use URLComponents (or something like WebURL or just URL) instead anyway, as that will ensure the URL is always properly constructed.

2 Likes

Thanks Jon. Stringly-typing seems to be a hard habit to break…

This isn't what's referred to as string interpolation in Swift, and as you've noted in your edit there isn't an overload of + that appends an Int to a String without explicit conversion. The diagnostic could be improved though.

2 Likes

Yes, sorry. Sloppy thinking from me there. I conflated addition of strings with interpolation as the outcomes are similar.

Somehow I don’t think that a job as a compiler engineer is in the cards for me…