Search code examples
swiftxcodeswiftuioption-type

SwiftUI struct property of optional protocol requirement is not accessible


I'm struggling since days with the extension of Matteo Manferdinis networking architecture from this link https://matteomanferdini.com/swift-rest-api/#send-data-post-body

As the guideline shows only how to implement an GET method I need to POST data as well. So I introduced the optional body property to the ApiResource protocol:


protocol APIResource {
  associatedtype ModelType: Codable
  var baseUrl:      String            {get}
  var apiVersion:   String            {get}
  var path:         String            {get}
  var method:       HTTPMethod        {get}
  //  var headers:    [String: String]? {get}
  //  var parameters: [String: Any]?    {get}
  var filterStatus: String            {get}
  var body:         ModelType?        {get}
}

enum HTTPMethod: String {
  case get    = "GET"
  case post   = "POST"
}

extension APIResource {
  var filterStatus: String      {get {return ""}}
  var apiVersion:   String      {get {return ""}}
  var body:         ModelType?  {return nil}
  
  var url: URL {
    var components = URLComponents(string: baseUrl)!
    components.path = "\(apiVersion)\(path)"
    
    if filterStatus != "" {
      components.queryItems = [URLQueryItem(name: "status", value: filterStatus)]
    }
    return components.url!
  }
}

Then I build a PostItemStruct which applies to APIResource protocol and initialize the body property.


struct PostItemResource: APIResource {
  typealias ModelType = ItemType
  var baseUrl      = AWSAPI.baseUrl
  var apiVersion   = AWSAPI.version
  var path         = "/items/"
  var method       = HTTPMethod.post
  var body         : ItemType?
  
  init(item: ItemType) {
    self.body  = item
    self.path  = "/items/\(item.id)"
  }
}

My viewModel use the updateItem() function to declare resource and request and calls the request.execute() function.

 func updateItem() async {
    guard let item = item else { return }
    
    let resource = PostItemResource(item: item)
    let request = APIRequest(resource: resource)
    
    errorMessage = nil
    
    do {
      try await request.execute()
    } catch {
      print((error as NSError).localizedFailureReason ?? "unknownError")
    }
  }

The request.execute() function will check whether its an get / or post method and in this case it will call the upload(resource) function from the NetworkRequest protocol.

  func execute() async throws -> (urlResponse: URLResponse, data: ModelType?) {
    switch resource.method {
    case .get:
      try await load(resource.url)
    case .post:
      try await upload(resource)
    }
  }

This brings us to the pain point where I cannot understand anymore what happens:

func upload(_ postData: any APIResource) async throws -> (urlResponse: URLResponse, data: ModelType?) {
    var request = URLRequest(url: postData.url)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    print("\n\nFull postData:")
    dump(postData)
    
    print("\n\npostData.body:")
    dump(postData.body)
    
    guard let body = postData.body else {throw NetworkError.invalidInput}
    request.httpBody = try encode(body as! Self.ModelType)
    
    let (data, response) = try await URLSession.shared.data(for: request)
    
    return try (response, decode(data))
  }
}

Here I'd expect that postData.body contains my data to be uploaded. But a dump(postData.body) gives me a nil as well as the guard throws me out of the function. BUT a dump(postData) is giving me an output which shows that the body is not nil.

Below you see the console with both dumps of my upload function. Can anyone explain why the postData.body converts to nil when directly addressed?

Full postData:
▿ App.PostItemResource
  - baseUrl: "xxxx"
  - apiVersion: "/beta"
  - path: "/item/498AEF35-844E-467E-A782-E1FFF11D4CCA"
  - method: App.HTTPMethod.post
  ▿ body: App.ItemType
    - id: "498AEF35-844E-467E-A782-E1FFF11D4CCA"
    ▿ version: Optional(0)
      - some: 0
    - type: App.MyType.einTyp
    - status: App.MyStatus.stock


postData.body:
- nil

On multiple levels of the architecture tried to dump the data and everywhere it works fine until right before the URLSession. Here the postData.body becomes nil for an unclear reason.


Solution

  • APIResource requires this:

    var body: ModelType? { get }
    

    In PostItemResource, ModelType is ItemType, so there should be a

    var body: ItemType? { get }
    

    But instead you wrote:

    var body: ItemType
    

    which does not satisfy the protocol requirement. The protocol requirement is instead satisfied by the default implementation you declared in the extension, which simply returns nil.

    So just declare body as optional and everything should be fine.

    var body: ItemType?
    

    If you want to prevent people from accidentally setting body to nil, you can change it to let, or have a dedicated method for setting it:

    private(set) var body: ItemType?
    
    func setBody(_ item: ItemType) {
        body = item
    }