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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
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!
}
}
</code>
<code> 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! } } </code>

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>
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)"
}
}
</code>
<code> 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)" } } </code>

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> 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")
}
}
</code>
<code> 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") } } </code>
 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> func execute() async throws -> (urlResponse: URLResponse, data: ModelType?) {
switch resource.method {
case .get:
try await load(resource.url)
case .post:
try await upload(resource)
}
}
</code>
<code> func execute() async throws -> (urlResponse: URLResponse, data: ModelType?) { switch resource.method { case .get: try await load(resource.url) case .post: try await upload(resource) } } </code>
  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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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("nnFull postData:")
dump(postData)
print("nnpostData.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))
}
}
</code>
<code>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("nnFull postData:") dump(postData) print("nnpostData.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)) } } </code>
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("nnFull postData:")
    dump(postData)
    
    print("nnpostData.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?

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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
</code>
<code>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 </code>
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.

APIResource requires this:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var body: ModelType? { get }
</code>
<code>var body: ModelType? { get } </code>
var body: ModelType? { get }

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var body: ItemType? { get }
</code>
<code>var body: ItemType? { get } </code>
var body: ItemType? { get }

But instead you wrote:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var body: ItemType
</code>
<code>var body: ItemType </code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>var body: ItemType?
</code>
<code>var body: ItemType? </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>private(set) var body: ItemType?
func setBody(_ item: ItemType) {
body = item
}
</code>
<code>private(set) var body: ItemType? func setBody(_ item: ItemType) { body = item } </code>
private(set) var body: ItemType?

func setBody(_ item: ItemType) {
    body = item
}

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật