Module 2 - Lesson 16 Wrap up challenge very much stuck

Hi guys,

This is my first post on here. I hope someone can help me as I am absolutely stuck. I am on lesson 16 of module 2, the final wrap up challenge. I created my own json file and used a json validator to verify the file and it comes back as a valid json file. When I press cmd+B to build the app, the build completes without any errors, however the main view is just a blank navigation view with a navigation bar title and nothing else.

My code is below:
import Foundation

class AuthorModel: ObservableObject {

@Published var authors = [Author]()

init() {
    self.authors = getLocalData()
}

func getLocalData() -> [Author] {
    
    let pathString = Bundle.main.path(forResource: "data", ofType: "json")
    
    if let pathString = pathString {
        
        let url = URL(fileURLWithPath: pathString)
        
        do{
            let data = try Data(contentsOf: url)
            
            let decoder = JSONDecoder()
            var authors = try decoder.decode([Author].self, from: data)
            
            for index in 0..<authors.count{
                authors[index].id = UUID()
            }
            self.authors = authors
            
        }
        catch {
            print(error)
        }
    }
    
    
    return [Author]()
}

}
import Foundation

struct Author: Decodable, Identifiable {

var id:UUID?

var name:String

var image:String

var authorImage:String

var aboutImage:String

var aboutauthor:String

var quotes:[String]

}

struct MockData {

static let sampleQuote = Author(id: UUID(), name: “dAVE”, image: “calm”, authorImage: “xiv”, aboutImage: “Man at box”, aboutauthor: “The was a idiot”, quotes: [“quote one”, “quote2”])

static let famous = [sampleQuote, sampleQuote, sampleQuote,sampleQuote]

}

The ContentView:

import SwiftUI

struct ContentView: View {

@ObservedObject var model = AuthorModel()

var body: some View {
    NavigationView {
        ScrollView{
            VStack(alignment: .leading, spacing: 20){
                ForEach(model.authors) { a in
                    NavigationLink(destination: DetailView(author: a),
                    label: {
                        Card(author: a)
                    })
                }
            }
            
        }
        .navigationBarTitle("Famous Quotes")
    }
}

}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

The DetailView:

import SwiftUI

struct DetailView: View {

var author: Author?
var body: some View {
    
    if let author = author {
        ScrollView {
            
            VStack{
                Image(author.authorImage)
                    .resizable()
                    .scaledToFit()
                //.aspectRatio(contentMode: .fit)
                Divider()
                
                Spacer()
                VStack(alignment: .center){
                    Text(author.aboutImage)
                        .font(.subheadline)
                    Divider()
                    Text(author.aboutauthor)
                        .font(.body)
                    Divider()
                    
                }
                
                VStack {
                    
                    ForEach(author.quotes, id: \.self) {quote  in
                        Text(quote)
                    }
                    Spacer()
                }
                
            }
            .padding([.leading, .trailing], 10)
            
            
        }
    }
}

}

struct DetailView_Previews: PreviewProvider {
    static var previews: some View {
        DetailView(author: MockData.famous[1])
    }
}

The Card view:
import SwiftUI

struct Card: View {

var author: Author
var body: some View {
    ZStack{
        Image(author.image)
            .resizable()
            .aspectRatio(contentMode: .fill)
            .cornerRadius(15)
        
        VStack{
            if author.quotes.count > 0 {
                Text(author.quotes[0])
                    .font(.largeTitle)
                    .fontWeight(.bold)
            }
            Text("- " + author.name)
        }
        .padding([.top, .leading], 20.0)
        .shadow(color: .black, radius: 10, x: 2, y: 2)
        }
        .foregroundColor(Color.white)
        .frame(width: .none, height: 400, alignment: .center)
        .clipped()
        .cornerRadius(15)
        .padding([.leading, .trailing])
    }
}

struct Card_Previews: PreviewProvider {
    static var previews: some View {
        Card(author: MockData.famous[0])
    }
}

The JSON File:
[
{
“name”:“Napoleon”,
“authorImage”:“Napoleon”,
“image”:“ambition”,
“aboutImage”: “Napoleon on the Imperial Throne”,
“aboutauthor”: “Napoleon, also Napoleon Bonaparte, and later known by his regnal name Napoleon I, was a French military and political leader who rose to prominence during the French Revolution and led several successful campaigns during the Revolutionary Wars.”,
“quotes”: [“Never interrupt your enemy when he is making a mistake”,
“A soldier will fight long and hard for a bit of colored ribbon”,
“History is a set of lies agreed upon”,
“Death is nothing, but to live defeated and inglorious is to die die daily”,
“Regilion is what keeps the poor from murbering the rich”,
“In politics stupidity is not a handicap”,
“Impossible is a word to be found only in the dictionary of fools”,
“A leader is da dealer in hope”,
“Victory belongs to the most perservering”,
“If you wish to be a success in the world, promise everything, deliver nothing”,
“I can no longer obey; I have tasted command, i cannot give it up”,
“The battlefield is a scene of constant chaos. The winner will be the one who controls that chaos, both his own and the enemies”,
“There are only two forces in the world, the sword and the spirit. In the long run the sword will always be conquered by the spirit”,
“Four hostile newspapers are more to be feared than a thousand bayonets”,
“Glory is fleeting, but obscurity is forever”,
“Men are moved by two levers only, fear and self interest”,
“A true man hates no one”,
“Great ambition is the passio of a great character. Those endowed with it may perform very good or very bad acts. It depends on the principles which direct them”,
“There are no such thing as accident, it is fate misnamed”,
“A army marches on its stomach”,
“He who fears being conqquered is sure of defeat”,
“Ten people who speak make more noise than ten thousand who are silent”,
“From the heights of thses pyramids, fourty centuries look down on us”,
“Ability is nothing wwithout opporrtunity”,
“Men are more easily goverend though their vices than through their virtues”,
“Take time to deliberate, but when the time for action has arrived, stop thinking and go in”,
“Power is my mistress. I have worked too hard at her conquest to allow anyone to take her away from me”,
“The surest way to remain poor is to be a honest man”,
“Soldiers wins battles; generals get the credit for it”,
“The people to fear are not those who disagree with you, but those wo disagree with you and are too cowardly to let you know”,
“Throw off your worries when you throu off your clothes at night”,
“Music is the voise that tells us that the human race is greater than it knows”,
“I am sometimes a fox and sometimes a lion. The whole secret of goverment lies in knowing when to be the one or the other”,
“A man will fight harder for his interests than for his rights”,
“A throne is only a bench vovered with velvet”,
“A revolution is an idea which has found its bayonets”,
“One must change one’s tactics every ten years if one wishes to main one’s superiority”,
“The best way to keep one’s word is not to give it”,
“Public opinion is the thermometer a monarch should constantly consult”,
“Men take only their needs into consideration - never their aabilities”,
“There is only one kind of robber whom the law does not strike at and who steals what is most precious to men: Time”,
“Respect the burden”,
“A constitution should be short and obscure”,
“Among those who dislike oppression are many who like to oppress”,
“A celerated people lose dignity upon a closer view”,
“France has more need of me than I have the need of France”,
“Riches do not consist in the possession of tresures, but in the use made of them”,
“The torment of precautions often exceeds the dangers to be avoided. It is sometimes better to abaandon one’s self to destiny”,
“A revolution can neither be made or stopped. The only thing that can be done is for several of its children to give it a direction by dint of victories”,
“When small man attempt great enterprises, they always end up reducing them to the level of their mediocrity”,
“I made all my generals out of mud”,
“Religion is excellent stuff for keeping the common people quite”,
“I am the successor, not of Louis XVI, but of Charlemagne”,
“The extent of your consciousness is limited only by your ablity to love and to embrace with your love the space around you, and all it contains”,
“The army is the true nobility of our country”,
“War is the business of barbarians”,
“The act of policing is, in order to punish less often, but to punish more severely”,
“I have only one council for you - be master”,
“The French complaain of everything, and always”,
“It is my wish that my ashes may repose on the banks of the Seine, in the midst of the French people, whom I have loved so well”,
“The infectiousness of crime is like that of the plague”,
“With aaudacity one can undertake anything, but not do everything”,
“The great proof of madness is the disproportion of one’s designs to one’s means”,
“The battle of Austerlitz is the grandest of all I have fought”
]
},
{
“name”:“Lenin”,
“authorImage”: “Lenin”,
“image”:“ambition”,
“aboutImage”: “Lenin arriving at Finland Station, Petrograd, 1917”,
“aboutauthor”: “Vladimir Ilyich Ulyanov, better known as Vladimir Lenin, was a Russian revolutionary, politician, and political theorist. He served as the first and founding head of government of Soviet Russia from 1917 to 1924 and of the Soviet Union from 1922 to 1924.”,
“quotes”: [“Give me four years to teach the children and the seed I have sown will never be uprooted”,
“The way to cruch the bourgeoisie is t grind them between the milestones of taxation and inflation”,
“A lie told often enough becomes the truth”,
“The goal of socialism is communism”,
“One man with a gun can control 100 without one”,
“The best way to destroy the capitalist system is to debaunch the currency”,
“There are no morals in politics; there is only expedience. A scoundral may be of use to us because he is a scoundral”,
“Sometimes history needs a push”,
“It is true that liberty is precious, so precious that it must be carefully rationed”,
“Without revolutionry theory there can be no revolutioary movement”,
“Dispair is typical of those who do not understand the causes of eveil, see no way out, and are incapable of struggle. The modern industrial proletariat does not belong to the catergory of such classes”,
“Crime is a product of social excess”,
“When there is state there can be no freedom, but when there is freedom there will be no state”,
“Any cook should be aable to run the country”,
“The oppressed are allowed once very few yers to decide which particular representtives of the oppressing class are to represent and repress them in parliament”,
“Can a nation be free if it oppresses other nations? It cannot”
]
},
{
“name”: “Marcus Aurelius”,
“authorImage”: “MSR”,
“image”:“reflect”,
“aboutImage”: “Marble bust, Musee Saint-Raymond”,
“aboutauthor”: “arcus Aurelius Antoninus was Roman emperor from 161 to 180 and a Stoic philosopher. He was the last of the rulers known as the Five Good Emperors, and the last emperor of the Pax Romana, an age of relative peace and stability for the Roman Empire lasting from 27 BC to 180 AD”,
“quotes”: [" When you rise in the morning, think of what a precious privilege it is to be alive - to breathe, to think, to enjoy, to love",
“The happiness of your life depends upon the quality of your thoughts: therefore, guard accordingly, and take care that you entertain no notions unsuitaable to virtue and reasonable nature”,
“It is not death that a man should fear, but he should fear never beginning to live”,
“Accept the things to which fate binds you, and love the people with brings together, but do so with all your heart”,
“Reject your sense of injury and the injury itself dissapears”,
“You have power over your mind - not outside events. Realize this, and you will find strength”,
“Never let the future disturb you. You will meet it, if you have to, with the same weapons of reason wwhich today arm you against the present”,
“The best revenge is to be unlikehim who performed the injury”,
“Nothing happens to any man that he is not formed by nature to bear”,
“Life is neither good or evil, but only a place for good and evil”,
“The soul becomes dyed with the color of its thoughts”,
“Our life is what our thoughts make it”,
“Time is a sort of river of passing events, and strong is its current, no sooner is a thing brought to sight than it is swept by and another takes its place, and this too will be swept away”,
“He who lives in harmony with himself lives in harmony with the universe”,
“Be like a rocky promontory against which the restless surf continually pounds; it stands fast while the churning sea is lulled to sleep at its feet. I hear you say, How unlucky that this should happen to me! Not at all! Say instead, How lucky that I am not broken by what has happened and am not afraid of what is about to happen. The same blow might have struck anyone, but not many would have absorbed it without capitulation or complaint”,
“If thou art pained by any external thing, it is not this that disturbs thee, but thy own judgment about it. And it is in thy power to wipe out this judgment now”,
“A cucumber is bitter. Throw it away. There are briars in the road. Turn aside from them. This is enough. Do not add, And why were such things made in the world?”,
“Put an end once for all to this discussion of what a good man should be, and be one.”,
“Soon you’ll be ashes or bones. A mere name at most—and even that is just a sound, an echo. The things we want in life are empty, stale, trivial.”,
“Never regard something as doing you good if it makes you betray a trust or lose your sense of shame or makes you show hatred, suspicion, ill-will or hypocrisy or a desire for things best done behind closed doors.”,
“Not to feel exasperated or defeated or despondent because your days aren’t packed with wise and moral actions. But to get back up when you fail, to celebrate behaving like a human—however imperfectly—and fully embrace the pursuit you’ve embarked on.”,
“Let opinion be taken away, and no man will think himself wronged. If no man shall think himself wronged, then is there no more any such thing as wrong.”,
“As for others whose lives are not so ordered, he reminds himself constantly of the characters they exhibit daily and nightly at home and abroad, and of the sort of society they frequent; and the approval of such men, who do not even stand well in their own eyes has no value for him.”,
“Shame on the soul, to falter on the road of life while the body still perseveres.”,
“Whatever happens to you has been waiting to happen since the beginning of time. The twining strands of fate wove both of them together: your own existence and the things that happen to you.”,
“In your actions, don’t procrastinate. In your conversations, don’t confuse. In your thoughts, don’t wander. In your soul, don’t be passive or aggressive. In your life, don’t be all about business”,
“Before making a decision The first thing to do – don’t get worked up. For everything happens according to the nature of all things, and in a short time you’ll be nobody and nowhere even as the great emperors Hadrian and Augustus are now. The next thing to do – consider carefully the task at hand for what it is, while remembering that your purpose is to be a good human being. Get straight to doing what nature requires of you, and speak as you see most just and fitting – with kindness, modesty, and sincerity.”,
“What if someone despises me? Let me see to it. But I will see to it that I won’t be found doing or saying anything contemptible. What if someone hates me? Let me see to that. But I will see to it that I’m kind and good-natured to all, and prepared to show even the hater where they went wrong. Not in a critical way, or to show off my patience, but genuinely and usefully.”,
“Do not act as if thou wert going to live ten thousand years. Death hangs over thee. While thou livest, while it is in thy power, be good”,
“Of the life of man the duration is but a point.”,
“A person who doesn’t know what the universe is doesn’t know who they are. A person who doesn’t know their purpose in life doesn’t know who they are or what the universe is. A person who doesn’t know any of these things doesn’t know why they are here. So what to make of people who seek or avoid the praise of those who have no knowledge of where or who they are?”,
“Often injustice lies in what you aren’t doing, not only in what you are doing.”,
“Whenever you suffer pain, keep in mind that it’s nothing to be ashamed of and that it can’t degrade your guiding intelligence, nor keep it from acting rationally and for the common good. And in most cases you should be helped by the saying of Epicurus, that pain is never unbearable or unending, so you can remember these limits and not add to them in your imagination. Remember too that many common annoyances are pain in disguise, such as sleepiness, fever and loss of appetite. When they start to get you down, tell yourself you are giving in to pain.”,
“Enough of this miserable, whining life. Stop monkeying around! Why are you troubled? What’s new here? What’s so confounding? The one responsible? Take a good look. Or just the matter itself? Then look at that. There’s nothing else to look at. And as far as the gods go, by now you could try being more straightforward and kind. It’s the same, whether you’ve examined these things for a hundred years, or only three.”,
“Keep this thought handy when you feel a bit of rage coming on – it isn’t manly to be enraged. Rather, gentleness and civility are more human, and therefore manlier. A real person doesn’t give way to anger and discontent, and such a person has strength, courage, and endurance – unlike the angry and complaining. The nearer a man comes to a calm mind, the closer he is to strength.”,
“Don’t tell yourself anything more than what the initial impressions report. It’s been reported to you that someone is speaking badly about you. This is the report – the report wasn’t that you’ve been harmed. I see that my son is sick – but not that his life is at risk. So always stay within your first impressions, and don’t add to them in your head – this way nothing can happen to you.”,
“Drama, combat, terror, numbness, and subservience – every day these things wipe out your sacred principles, whenever your mind entertains them uncritically or lets them slip in.”,
“I’m constantly amazed by how easily we love ourselves above all others, yet we put more stock in the opinions of others than in our own estimation of self…How much credence we give to the opinions our peers have of us and how little to our very own!”,
“Does the light of a lamp shine and keep its glow until its fuel is spent? Why shouldn’t your truth, justice, and self-control shine until you are extinguished?”
]
},
{
“name”: “Louis XIV”,
“authorImage”: “xiv”,
“image”:“reflect2”,
“aboutImage”: “Louis XIV, King of France at Versailles”,
“aboutauthor”: “Louis XIV, also known as Louis the Great or the Sun King, was King of France from 14 May 1643 until his death in 1715. His reign of 72 years and 110 days is the longest of any sovereign in history whose date is verifiable.”,
“quotes”: [“It is legal because I wish It”,
“I am the State”,
“There is little that can withstand a man who can conquer himself”,
“Ah, if I were not king, I should lose my temper”,
“Everytime I appoint someone to a vacant position, I make a hundred unhappy and one ungrateful”,
“It is impossible to please all of the world”,
“My child, you are going to be a great king, do not imitate me in the tast I have had for building, or in that I have had for war, try on the contrary, to be at peace with your neighbors”,
“The Pyrenees are no more”,
“Render to God what you owe him, recognize the obligations you are under to him”,
“I could sooner reconcile all Europe than two woman”,
“Has God forgotten all I have done for Him”,
“I am dying, but the state remains”,
“We can do all we wish while we live, afterward, we are less than the meanest”,
“The King of Spain displayed his esteem for me in a manner that I confess flattered me pleasantly when, after the deaath of Don Luis de Haro, he stated publicly in front of all the foreign ambassadors that he wanted to follow my example in not having a prime minister any longer”,
“My court was divided between peace and war according to their various interests, but I considered only their resons”,
“Always follow good counsels”,
“First feelings are always the most natural”,
“That’s what troubles me, I should like to suffer more for the expiation of my sins”,
“Laws are the sovereigns of sovereigns”,
“You have only to see what became of my father’s will immediately after his deaath, and the wills of so many other kings. I know it well, but nevertheless, they have wished it, they gave me no rest nor repose, no calm until it was done”,
“I have made my will, I have been tormented to do it. I have bought repose, I know the powerlessness and inutility of it”,
“The ministers of kings should learn to moderate their ambition. The higher they elevate themselves above their proper sphere, the greater the danger that they will fall”,
“As for restitutions, to nobody in particular do I owe any, but as for those I owe to the realm, I have hope in the mercy of God”
]
}
]

I am totally stuck and need help

Thanks in advance

Paul

Hi Paul,

Welcome to the community.

To save considerable time, can you compress your project into a zip file and then post that to either DropBox or Google Drive and create a share link. Post that share link in a reply.

If you use Google Drive, when you create the share link can you set the General Access to “Anyone with the Link” rather than Restricted.

The problem may be that your getLocalData() is configured to return an array of Author but there is a missing return statement in the function.

Change

self.authors = authors

to

return authors

Hi Chris,

That worked!!!

Thank you so much for your help. I have spend days going around in circles trying to figure it out. Definitely learned something here.

Noted on the Dropbox or Google Drive suggestions.

On to the next modules and challenges

Regards

Paul