CompactMapValues 不适用于这个简单的字典

CompactMapValues not working on this simple dictionary

我的模型看起来像:

public struct Profile {
  public let bio: String?
  public let company: String
  public let createdDate: Date
  public let department: String
  public let email: String
  public let firstName: String
  public let coverImageURL: URL?
  public let jobTitle: String
  public let lastName: String
  public let location: String?
  public let name: String
  public let profileImageURL: URL?
  public let roles: [String]
  public let isActive: Bool
  public let updatedDate: Date?
  public let userID: String

  public init(
    bio: String?, company: String, createdDate: Date, department: String, email: String, firstName: String, coverImageURL: URL?, jobTitle: String,
    lastName: String, location: String?, name: String, profileImageURL: URL?, roles: [String], isActive: Bool, updatedDate: Date?, userID: String) {
    self.bio = bio
    self.company = company
    self.createdDate = createdDate
    self.department = department
    self.email = email
    self.firstName = firstName
    self.coverImageURL = coverImageURL
    self.jobTitle = jobTitle
    self.lastName = lastName
    self.location = location
    self.name = name
    self.profileImageURL = profileImageURL
    self.roles = roles
    self.isActive = isActive
    self.updatedDate = updatedDate
    self.userID = userID
  }


}

extension Profile: Equatable { }

我正在尝试创建一个将其表示为 (model: Profile, json: [String: Any])

的元组

使用以下方法-

  func makeProfile() -> (model: Profile, json: [String: Any]) {

    let updatedDate = Date()
    let updatedDateStr = updatedDate.toString(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX")
    let createdDate = Date()
    let createdDateStr = createdDate.toString(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX")

    let coverImageURL = makeURL("https://headerUri.com")
    let profileImageURL = makeURL("https://pictureUri.com")
    let model = Profile(
      bio: "Some Bio",
      company: "Cool Job INC",
      createdDate: createdDate,
      department: "Engineering",
      email: "name@domain.tld",
      firstName: "Anne",
      coverImageURL: coverImageURL,
      jobTitle: "Test Dummy",
      lastName: "Employee",
      location: "London",
      name: "Anne Employee",
      profileImageURL: profileImageURL,
      roles: ["ADMIN"],
      isActive: true,
      updatedDate: updatedDate,
      userID: UUID().uuidString
    )

    let json: [String: Any] = [
      "bio": model.bio,
      "company": model.company,
      "createdDate": createdDateStr,
      "department": model.department,
      "email": model.email,
      "firstName": model.firstName,
      "headerUri": model.coverImageURL?.absoluteString,
      "jobTitle": model.jobTitle,
      "lastName": model.lastName,
      "location": model.location,
      "name": model.name,
      "pictureUri": model.profileImageURL?.absoluteString,
      "roles": model.roles,
      "isActive": model.isActive,
      "updatedDate": updatedDateStr,
      "userId": model.userID
      ].compactMapValues { [=11=] }

    return (model: model, json: json)
  }
}

extension Date {
  func toString(dateFormat format: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = format
    return dateFormatter.string(from: self)
  }
}

所有可选属性都显示警告 Expression implicitly coerced from 'String?' to 'Any'

我已将 .compactMapValues { [=14=] } 添加到字典中,但没有任何效果。

如何清除此警告?

您收到警告是因为在您初始化字典时这些值是可选的。您的 .compactMapValues { [=11=] } 将无济于事,因为到那时它是 "too late".

相反,您可以初始化一个空字典并将值 1 乘 1 相加。

var json = [String: Any]()
json["bio"] = model.bio
json["company"] = model.company
// all of the other values
json["userId"] = model.userID

您收到错误消息是因为您试图隐式地将一个可选值(可能为 nil)强制转换为 Any,这隐藏了该值可能为 nil。

compactMapValues 不保证在编译时该值不为零;编译器只知道可选的东西(如 String?)现在被视为非可选的 Any.

避免错误的一种方法是提供默认值而不是可选值:

let json: [String: Any] = [
   "bio": model.bio ?? ""
    // ...
   ]

或者,您可以创建一个字典:[String, Any?] 为其赋值,然后使用 .compactMapValues,这将返回 Any 的非可选值。

let withOptionals: [String: Any?] = [
   "bio": model.bio,
   // ...
]

let json: [String, Any] = withOptionals.compactMapValues { [=11=] }