Accessing properties of a [Struct]
I'm attempting to get certain pieces of JSON data to populate a table view, and I'm not sure how to access these properties without running into an index out of range error.
I'm getting the data from the IEX API (JSON):
fetchData(url: stockApiUrl) { (result: FetchResult<[String:Stock]>) -> (Void) in
switch result {
case .success(let object):
self.stockData = object
self.keys = Array(object.keys)
print("stockData: nn(self.stockData)")
case .failure(let error):
print("Error decoding JSON: nn(error)")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
And using these structs to decode:
struct Welcome: Decodable {
let aapl, fb, msft, tsla, goog: Stock
enum CodingKeys: String, CodingKey {
case aapl = "AAPL"
case fb = "FB"
case msft = "MSFT"
case tsla = "TSLA"
case goog = "GOOG"
}
}
struct Stock: Decodable {
let quote: Quote
let news: [News]
}
struct Quote: Decodable {
let symbol: String
let companyName: String
let latestPrice: Double
}
struct News: Decodable {
let url: String
let image: String
}
The resulting data is set to a dictionary, and there's a keys variable so I can access to keys:
var stockData = [String:Stock]()
var keys = [String]()
Accessing the properties of Stock and Quote is ok, but I have an array of the News struct within Stock, and this is what's throwing me off. My goal is to use the url property of News in my didSelectRow method so I can use WebKit to load the company's url when a cell is tapped:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let stock = stockData[keys[indexPath.row]]!
guard let webUrl = URL(string: stock.news[1].url) else {return}
print("nnnwebUrls:nnnnn(webUrl)nnnn")
let webController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "webController") as! WebViewController
webView.load(URLRequest(url: webUrl))
webController.view = webView
self.navigationController?.pushViewController(webController, animated: true)
}
As you can see I've attempted accessing the properties with
guard let webUrl = URL(string: stock.news[1].url) else {return}
And printing webUrl successfully prints all of the urls, however they're all separate, as you can see here:

Because of this, webView.load(URLRequest(url: webUrl) is only getting one url (the first one) instead of all of them, resulting in the out of range error.
I'm wondering how I can change this to get all of the urls together instead of separate.
swift struct
add a comment |
I'm attempting to get certain pieces of JSON data to populate a table view, and I'm not sure how to access these properties without running into an index out of range error.
I'm getting the data from the IEX API (JSON):
fetchData(url: stockApiUrl) { (result: FetchResult<[String:Stock]>) -> (Void) in
switch result {
case .success(let object):
self.stockData = object
self.keys = Array(object.keys)
print("stockData: nn(self.stockData)")
case .failure(let error):
print("Error decoding JSON: nn(error)")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
And using these structs to decode:
struct Welcome: Decodable {
let aapl, fb, msft, tsla, goog: Stock
enum CodingKeys: String, CodingKey {
case aapl = "AAPL"
case fb = "FB"
case msft = "MSFT"
case tsla = "TSLA"
case goog = "GOOG"
}
}
struct Stock: Decodable {
let quote: Quote
let news: [News]
}
struct Quote: Decodable {
let symbol: String
let companyName: String
let latestPrice: Double
}
struct News: Decodable {
let url: String
let image: String
}
The resulting data is set to a dictionary, and there's a keys variable so I can access to keys:
var stockData = [String:Stock]()
var keys = [String]()
Accessing the properties of Stock and Quote is ok, but I have an array of the News struct within Stock, and this is what's throwing me off. My goal is to use the url property of News in my didSelectRow method so I can use WebKit to load the company's url when a cell is tapped:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let stock = stockData[keys[indexPath.row]]!
guard let webUrl = URL(string: stock.news[1].url) else {return}
print("nnnwebUrls:nnnnn(webUrl)nnnn")
let webController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "webController") as! WebViewController
webView.load(URLRequest(url: webUrl))
webController.view = webView
self.navigationController?.pushViewController(webController, animated: true)
}
As you can see I've attempted accessing the properties with
guard let webUrl = URL(string: stock.news[1].url) else {return}
And printing webUrl successfully prints all of the urls, however they're all separate, as you can see here:

Because of this, webView.load(URLRequest(url: webUrl) is only getting one url (the first one) instead of all of them, resulting in the out of range error.
I'm wondering how I can change this to get all of the urls together instead of separate.
swift struct
I don’t get the problem, you explicitly fetch a news object from the array: news[1].url why would you expect webUrl having multiple values?
– JohnnyAW
Nov 14 '18 at 16:59
add a comment |
I'm attempting to get certain pieces of JSON data to populate a table view, and I'm not sure how to access these properties without running into an index out of range error.
I'm getting the data from the IEX API (JSON):
fetchData(url: stockApiUrl) { (result: FetchResult<[String:Stock]>) -> (Void) in
switch result {
case .success(let object):
self.stockData = object
self.keys = Array(object.keys)
print("stockData: nn(self.stockData)")
case .failure(let error):
print("Error decoding JSON: nn(error)")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
And using these structs to decode:
struct Welcome: Decodable {
let aapl, fb, msft, tsla, goog: Stock
enum CodingKeys: String, CodingKey {
case aapl = "AAPL"
case fb = "FB"
case msft = "MSFT"
case tsla = "TSLA"
case goog = "GOOG"
}
}
struct Stock: Decodable {
let quote: Quote
let news: [News]
}
struct Quote: Decodable {
let symbol: String
let companyName: String
let latestPrice: Double
}
struct News: Decodable {
let url: String
let image: String
}
The resulting data is set to a dictionary, and there's a keys variable so I can access to keys:
var stockData = [String:Stock]()
var keys = [String]()
Accessing the properties of Stock and Quote is ok, but I have an array of the News struct within Stock, and this is what's throwing me off. My goal is to use the url property of News in my didSelectRow method so I can use WebKit to load the company's url when a cell is tapped:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let stock = stockData[keys[indexPath.row]]!
guard let webUrl = URL(string: stock.news[1].url) else {return}
print("nnnwebUrls:nnnnn(webUrl)nnnn")
let webController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "webController") as! WebViewController
webView.load(URLRequest(url: webUrl))
webController.view = webView
self.navigationController?.pushViewController(webController, animated: true)
}
As you can see I've attempted accessing the properties with
guard let webUrl = URL(string: stock.news[1].url) else {return}
And printing webUrl successfully prints all of the urls, however they're all separate, as you can see here:

Because of this, webView.load(URLRequest(url: webUrl) is only getting one url (the first one) instead of all of them, resulting in the out of range error.
I'm wondering how I can change this to get all of the urls together instead of separate.
swift struct
I'm attempting to get certain pieces of JSON data to populate a table view, and I'm not sure how to access these properties without running into an index out of range error.
I'm getting the data from the IEX API (JSON):
fetchData(url: stockApiUrl) { (result: FetchResult<[String:Stock]>) -> (Void) in
switch result {
case .success(let object):
self.stockData = object
self.keys = Array(object.keys)
print("stockData: nn(self.stockData)")
case .failure(let error):
print("Error decoding JSON: nn(error)")
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
And using these structs to decode:
struct Welcome: Decodable {
let aapl, fb, msft, tsla, goog: Stock
enum CodingKeys: String, CodingKey {
case aapl = "AAPL"
case fb = "FB"
case msft = "MSFT"
case tsla = "TSLA"
case goog = "GOOG"
}
}
struct Stock: Decodable {
let quote: Quote
let news: [News]
}
struct Quote: Decodable {
let symbol: String
let companyName: String
let latestPrice: Double
}
struct News: Decodable {
let url: String
let image: String
}
The resulting data is set to a dictionary, and there's a keys variable so I can access to keys:
var stockData = [String:Stock]()
var keys = [String]()
Accessing the properties of Stock and Quote is ok, but I have an array of the News struct within Stock, and this is what's throwing me off. My goal is to use the url property of News in my didSelectRow method so I can use WebKit to load the company's url when a cell is tapped:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let stock = stockData[keys[indexPath.row]]!
guard let webUrl = URL(string: stock.news[1].url) else {return}
print("nnnwebUrls:nnnnn(webUrl)nnnn")
let webController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "webController") as! WebViewController
webView.load(URLRequest(url: webUrl))
webController.view = webView
self.navigationController?.pushViewController(webController, animated: true)
}
As you can see I've attempted accessing the properties with
guard let webUrl = URL(string: stock.news[1].url) else {return}
And printing webUrl successfully prints all of the urls, however they're all separate, as you can see here:

Because of this, webView.load(URLRequest(url: webUrl) is only getting one url (the first one) instead of all of them, resulting in the out of range error.
I'm wondering how I can change this to get all of the urls together instead of separate.
swift struct
swift struct
edited Nov 14 '18 at 16:49
KingTim
asked Nov 14 '18 at 16:44
KingTimKingTim
516820
516820
I don’t get the problem, you explicitly fetch a news object from the array: news[1].url why would you expect webUrl having multiple values?
– JohnnyAW
Nov 14 '18 at 16:59
add a comment |
I don’t get the problem, you explicitly fetch a news object from the array: news[1].url why would you expect webUrl having multiple values?
– JohnnyAW
Nov 14 '18 at 16:59
I don’t get the problem, you explicitly fetch a news object from the array: news[1].url why would you expect webUrl having multiple values?
– JohnnyAW
Nov 14 '18 at 16:59
I don’t get the problem, you explicitly fetch a news object from the array: news[1].url why would you expect webUrl having multiple values?
– JohnnyAW
Nov 14 '18 at 16:59
add a comment |
1 Answer
1
active
oldest
votes
ok, so basicly you struggle to iterate over an array if I understand it correct, here you are:
var urls = [String]()
stock.news.forEach { urls.append($0.url) }
print(urls)
That did it, thanks for your help!
– KingTim
Nov 16 '18 at 17:30
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305031%2faccessing-properties-of-a-struct%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
ok, so basicly you struggle to iterate over an array if I understand it correct, here you are:
var urls = [String]()
stock.news.forEach { urls.append($0.url) }
print(urls)
That did it, thanks for your help!
– KingTim
Nov 16 '18 at 17:30
add a comment |
ok, so basicly you struggle to iterate over an array if I understand it correct, here you are:
var urls = [String]()
stock.news.forEach { urls.append($0.url) }
print(urls)
That did it, thanks for your help!
– KingTim
Nov 16 '18 at 17:30
add a comment |
ok, so basicly you struggle to iterate over an array if I understand it correct, here you are:
var urls = [String]()
stock.news.forEach { urls.append($0.url) }
print(urls)
ok, so basicly you struggle to iterate over an array if I understand it correct, here you are:
var urls = [String]()
stock.news.forEach { urls.append($0.url) }
print(urls)
answered Nov 14 '18 at 21:23
JohnnyAWJohnnyAW
2,3041923
2,3041923
That did it, thanks for your help!
– KingTim
Nov 16 '18 at 17:30
add a comment |
That did it, thanks for your help!
– KingTim
Nov 16 '18 at 17:30
That did it, thanks for your help!
– KingTim
Nov 16 '18 at 17:30
That did it, thanks for your help!
– KingTim
Nov 16 '18 at 17:30
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53305031%2faccessing-properties-of-a-struct%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I don’t get the problem, you explicitly fetch a news object from the array: news[1].url why would you expect webUrl having multiple values?
– JohnnyAW
Nov 14 '18 at 16:59