Tuesday, November 10, 2026
HomeiOS Developmentios - Why is a struct nil after assigning it a worth?...

ios – Why is a struct nil after assigning it a worth? Swift

[ad_1]

I’m making an attempt to get knowledge from a struct which shops knowledge from an API request. Nonetheless, the struct is asserted nil when this system runs.

I believe the issue is likely to be:

-I’m not assigning the property of an occasion of a struct to a brand new view controller’s occasion of a struct’s property, the place each struct’s use Codable accurately within the earlier view controller/the view controller that pushes the brand new view controller which is the place the struct is claimed to be nil, onto the stack.

That is in VenueResultsViewController.swift:

detailViewVC.venues = venues[indexPath.row]
        
      navigationController?.pushViewController(detailViewVC, animated: true)

-The declaring of the construction that I’m making an attempt to entry knowledge from on the prime of the view controller the place I’m making an attempt to entry this construction in (the latest view controller) isn’t accomplished accurately.

That is in DetailViewController.swift:

var selectedVenueDetailInfo: SelectedVenueDetailInfo!

I am utilizing the Yelp Fusion API on this venture.

Code:

VenueResultsViewController.swift:

import UIKit
import CoreLocation

class VenueResultsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    //Print Verify.
    //Prints.
    func printCheckBeforeIBOutletTableViewCode() {
        print("Print Verify: Proper earlier than tableView IBOutlet code at prime of DetailViewController.swift file.")
    }
    
    @IBOutlet var tableView: UITableView!
    
    var venues: [Venue] = []
    
    //Print Verify.
    //Prints.
    func printCheckAfterIBOutletTableViewCode() {
        print("Print Verify: Proper after tableView IBOutlet code at prime of DetailViewController.swift file.")
    }
    
    override func viewDidLoad() {
        tremendous.viewDidLoad()
        
        //Operate requires print checks.
        //Prints.
        self.printCheckBeforeIBOutletTableViewCode()
        self.printCheckAfterIBOutletTableViewCode()
        
        tableView.register(UINib(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
        tableView.delegate = self
        tableView.dataSource = self
        
        //Print Verify.
        //Prints.
        print("Print Verify: Proper earlier than creating an occasion of YelpApi class, then making a job to make the API request.")
        
        let yelpApi = YelpApi(apiKey: "Api key")
        
        Job {
            do {
                self.venues = strive await yelpApi.searchBusiness(latitude: selectedLatitude, longitude: selectedLongitude, class: "class quary goes right here", sortBy: "type by quary goes right here")
                self.tableView.reloadData()
            } catch {
                    //Deal with error right here.
                    //Prints.
                    print("Error at catch block for venues search API request: (error)")
            }
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection part: Int) -> Int {
           return venues.rely
       }
       
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "CustomTableViewCell", for: indexPath) as! CustomTableViewCell
       
       //Particulars for customized desk view cell go right here.
    }
       
    //Extra desk view protocol capabilities.
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        //*Code for assigning values to variables associated to what row within the desk view the person chosen.*
        
        
        let storyboard = UIStoryboard(title: "Primary", bundle: nil)
        let detailViewVC = storyboard.instantiateViewController(identifier: "NewViewController") as! NewViewController
        detailViewVC.modalPresentationStyle = .fullScreen
        detailViewVC.modalTransitionStyle = .crossDissolve
        
        
        //Unique Model I used to be utilizing earlier than refactoring to utilizing Codable and utilizing async/await to make the API request.
        //Errors I'd get for the under line of commented out code.: 1) use as! Decoder and a pair of) use "from:" as a substitute of "id". Every time I did these really helpful "fixes", and the next options to incorporate a do-catch block with a strive within the do block, and a "throws" on the finish of the perform definition, this nonetheless did not work.
    //        detailViewVC.venues = Venue(id: venues[indexPath.row].id)
        
        //V2: Giving me the most effective outcomes, however appears to be associated to drawback.
        detailViewVC.venues = venues[indexPath.row]
        
        //Print Verify.
        //Prints.
        print("Print Verify: Proper earlier than code for presenting the element view controller.")

        navigationController?.pushViewController(detailViewVC, animated: true)
        
    }
}

DetailViewController.swift:

class DetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet var detailsTableView: UITableView!
    
    var venues: Venue!
    
    var selectedVenueDetailInfo: SelectedVenueDetailInfo!
    
    override func viewDidLoad() {
        tremendous.viewDidLoad()
        
        //Registering nib for desk view.
        tableView.delegate = self
        tableView.dataSource = self
        
        let yelpApiSelectedVenueDetailInfo = YelpApiSelectedVenueDetailInfo(apiKey: "Api key")
        
        Job {
            do {
                self.selectedVenueDetailInfo = strive await YelpApiSelectedVenueDetailInfo.searchBusinessDetailsInfo(selectedVenueID: venues.id)
                self.detailsTableView.reloadData()
            } catch {
                    //Deal with error right here.
                    //Does not Print.
                    print("Error information for catch block in Job block in DetailsViewController for making API request: (error)")
            }
        }

        //Print Verify.
        //Prints nil.
        print("Print Verify: selectedVenueDetailInfo:", selectedVenueDetailInfo)
    
    }    


    //Desk View Protocol Capabilities.
    //TableView Capabilities
    func tableView(_ tableView: UITableView, numberOfRowsInSection part: Int) -> Int {

        return Some Quantity
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        //Code for when to point out customized cell, creating new variable for customized cell, and returning that customized cell. Will do that for a number of customized cells.
        if indexPath.row == 0 {
            let detailsPictureCustomCell = detailsTableView.dequeueReusableCell(withIdentifier: "DetailsPictureTableViewCell", for: indexPath) as! DetailsPictureTableViewCell
            
            
            //Print Verify.
            //Prints nil. Additionally, an error message is printed at the place "selectedVenueDetailInfo.id" earlier than the closing parenthesis within the code under when program is ran: "Thread 1: Deadly error: Unexpectedly discovered nil whereas implicitly unwrapping an Elective worth".
            print("Print Verify: selectedVenueDetailInfo.id:", selectedVenueDetailInfo.id)

detailsPictureCustomCell.venuePicture.loadFrom(URLAddress: selectedVenueDetailInfo.image_url ?? "string for place holder image")
            
        //Remainder of this perform.
    }
    
    //Remainder of Desk View Protocol Capabilities.
                
}

SelectedVenueDetailInfo.swift:

import Basis

// MARK: - SelectedVenueDetailInfo
struct SelectedVenueDetailInfo: Codable {
    let score: Double
    let value, cellphone, alias: String?
    let id: String
    let is_closed: Bool?
    let classes: [CategoryOfSelectedVenueForDetailInfo]
    let reviewCount: Int?
    let title: String
    let url: String?
    let coordinates: Heart
    let imageURL: String?
    let location: LocationOfSelectedVenueForDetailInfo
    let distance: Double
    let transactions: [String]
    let images: [String]?
}

// MARK: - CategoryOfSelectedVenueForDetailInfo
struct CategoryOfSelectedVenueForDetailInfo: Codable {
    let alias, title: String
}

// MARK: - CenterOfSelectedVenueForDetailInfo
struct CenterOfSelectedVenueForDetailInfo: Codable {
    let latitude, longitude: Double
}

// MARK: - LocationOfSelectedVenueForDetailInfo
struct LocationOfSelectedVenueForDetailInfo: Codable {
    let metropolis, nation, address2, address3: String?
    let state, address1, zipCode: String?
}

// MARK: - RegionOfSelectedVenueForDetailInfo
struct RegionOfSelectedVenueForDetailInfo: Codable {
    let middle: Heart
}

Venue.swift

import Basis

// MARK: - BusinessSearchResult
struct BusinessSearchResult: Codable {
    let whole: Int
    let companies: [Venue]
    let area: Area
}

// MARK: - Venue
struct Venue: Codable {
    let score: Double
    let value, cellphone, alias: String?
    let id: String
    let is_closed: Bool?
    let classes: [Category]
    let reviewCount: Int?
    let title: String
    let url: String?
    let coordinates: Heart
    let imageURL: String?
    let location: LocationOfVenue
    let distance: Double
    let transactions: [String]
}

// MARK: - Class
struct Class: Codable {
    let alias, title: String
}

// MARK: - Heart
struct Heart: Codable {
    let latitude, longitude: Double
}

// MARK: - LocationOfVenue
struct LocationOfVenue: Codable {
    let metropolis, nation, address2, address3: String?
    let state, address1, zipCode: String?
}

// MARK: - Area
struct Area: Codable {
    let middle: Heart
}

FetchSelectedVenueDetailInfo.swift:

import Basis
import CoreLocation

class YelpApiSelectedVenueDetailInfo {
    
    //Print Verify.
    //Does not print.
    func printCheck() {
        print("Print Verify: Line at prime/verybeggening of YelpApiSelectedVenueDetailInfo class.")
    }
    
    personal var apiKey: String
    
    init(apiKey: String) {
        self.apiKey = apiKey
    }
    
    func searchBusinessDetailsInfo(selectedRestaurantBusinessID: String) async throws -> SelectedVenueDetailInfo {
        
        
        // MARK: Make URL Request.
            
        //Print Verify.
        //Does not print.
        print("Print Verify: Line earlier than makign URLcomponents.")
        
        var urlComponents = URLComponents(string: "https://api.yelp.com/v3/companies/(selectedRestaurantBusinessID)")
        
        guard let url = urlComponents?.url else {
            throw URLError(.badURL)
        }
        
        //Print Verify.
        //Does not print.
        print("Print Verify: Line earlier than setting 'request' variable.")
        
        var request = URLRequest(url: url)
        request.setValue("Bearer (self.apiKey)", forHTTPHeaderField: "Authorization")
        
        //Print Verify.
        //Does not print.
        print("Print Verify: Earlier than 'let (knowledge, _) = strive await' line of code.")
        
        let (knowledge, _) = strive await URLSession.shared.knowledge(for: request)
        
        //Print Verify for printing the JSON knowledge.
        print(String(decoding: knowledge, as: UTF8.self))

        
        //Print Verify.
        //Does not print.
        print("Print Verify: Earlier than 'let businessDetailInfoResults = strive JSONDecoder()' line of code.")
        
        let businessDetailInfoResults = strive JSONDecoder().decode(SelectedVenueDetailInfo.self, from: knowledge)
        
        //Print Verify.
        //Does not print.
        print("Print Verify: Proper after 'let businessDetailInfoResults = strive JSONDecoder()' line of code.")

        //Print Verify.
        //Does not print.
        print("Print Verify: Earlier than 'return businessDetailViewInfoResults' code.")
        
        return businessDetailViewInfoResults
    }
}

FetchData.swift:

import Basis
import CoreLocation

class YelpApi {
    
    personal var apiKey: String
    
    init(apiKey: String) {
        self.apiKey = apiKey
    }
    
    func searchBusiness(latitude: Double,
                        longitude: Double,
                        class: String,
                        sortBy: String) async throws -> [Venue] {
        
        var queryItems = [URLQueryItem]()
        queryItems.append(URLQueryItem(title:"latitude",worth:"(latitude)"))
        queryItems.append(URLQueryItem(title:"longitude",worth:"(longitude)"))
        queryItems.append(URLQueryItem(title:"classes", worth:class))
        queryItems.append(URLQueryItem(title:"sort_by",worth:sortBy))
       
        var outcomes = [Venue]()
        
        var expectedCount = 0
        let countLimit = 50
        var offset = 0
        
        queryItems.append(URLQueryItem(title:"restrict", worth:"(countLimit)"))
        
        
        repeat {
            
            var offsetQueryItems = queryItems
            
            offsetQueryItems.append(URLQueryItem(title:"offset",worth: "(offset)"))
            
            var urlComponents = URLComponents(string: "https://api.yelp.com/v3/companies/search")
            urlComponents?.queryItems = offsetQueryItems
            
            guard let url = urlComponents?.url else {
                throw URLError(.badURL)
            }
            
            var request = URLRequest(url: url)
            request.setValue("Bearer (self.apiKey)", forHTTPHeaderField: "Authorization")
            
            let (knowledge, _) = strive await URLSession.shared.knowledge(for: request)
            
            let businessResults = strive JSONDecoder().decode(BusinessSearchResult.self, from:knowledge)
            
            expectedCount = min(businessResults.whole,1000)
            
            outcomes.append(contentsOf: businessResults.companies)
            offset += businessResults.companies.rely
        } whereas (outcomes.rely < expectedCount)
        
        
        return outcomes
    }
}

Thanks!

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments