所以我在这里有一段代码不起作用.这是因为它在尝试解包可选值时发现了nil.这是因为它在异步方法中被初始化.我的问题是,在取出结果之前,我该如何推迟返回函数? struct Domain { var n
struct Domain { var name: String? var tld: String? var combined: String { get { return self.name!+self.tld! } } var whoIs: String { get { if self.whoIs.isEmpty { var result: String? dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let whois_url = NSURL(string: SEARCH_URL+self.combined+"/whois") result = NSString(contentsOfURL: whois_url!, encoding: NSUTF8StringEncoding, error: nil) print(result!) }) return result! } return self.whoIs } } }如果要等待块的结果,只需使用dispatch_sync替换dispatch_async:
dispatch_sync(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { let whois_url = NSURL(string: SEARCH_URL+self.combined+"/whois") result = NSString(contentsOfURL: whois_url!, encoding: NSUTF8StringEncoding, error: nil) print(result!) })
这将确保在将URL的内容提取到结果中之前不返回该方法.