Groups | Search | Server Info | Login | Register


Groups > comp.sys.mac.programmer.misc > #213

I don't understand why this Swift 2 String() won't init

From Mike <mikee@mikee.ath.cx>
Newsgroups comp.sys.mac.programmer.help, comp.sys.mac.programmer.misc
Subject I don't understand why this Swift 2 String() won't init
Followup-To comp.sys.mac.programmer.help
Date 2015-12-11 21:30 +0000
Organization A noiseless patient Spider
Message-ID <n4ff9e$5ul$2@dont-email.me> (permalink)

Cross-posted to 2 groups.

Followups directed to: comp.sys.mac.programmer.help

Show all headers | View raw


I have this code in an os x playground (XCode Version 7.2 (7C68)):

let urlString = "https://news.google.com"
let url = NSURL(string: urlString)!
let listData = NSData(contentsOfURL: url)!
var dataString = String(data: listData, encoding: NSUTF8StringEncoding)
print(dataString)


and what seems to me to be equilivent code in an OS X app I'm building:

static func httpRequest(urlString: String) -> String {
	if let url = NSURL(string: urlString) {
		if let urlData = NSData(contentsOfURL: url) {
			return String(data: urlData, encoding: NSUTF8StringEncoding) ?? "httpRequest: string failed"
			//var dataString = String(data: listData, encoding: NSUTF8StringEncoding)
		} else {
			return "httpRequest: nsdata failed"
		}
	} else {
		return "httpRequest: nsurl failed"
	}
}

The "if let" constructs I added to find out what was happening. I
could use one of the several wrappers around the HTTP get/et. al.,
but I want to understand myself what's happening before I trust
other code.

In the playground the extraction from NSData works and the large
(56K?) string is printed. In the OS X app the String() fails and I
don't understand why.

Why does the String() creation in the OS X app fail?

TIA

(I'm using the "static func" construct inside a "struct" because
this is the only way I have found to create tests without error.)

(I've cross posted this to three groups total to get an answer.)

Mike

Back to comp.sys.mac.programmer.misc | Previous | Next | Find similar


Thread

I don't understand why this Swift 2 String() won't init Mike <mikee@mikee.ath.cx> - 2015-12-11 21:30 +0000

csiph-web