Skip to main content
 首页 » 数据库

ios之无法将表达式类型 'Dictionary' 转换为类型 'StringLiteralConvertible'

2024年01月01日73daizhj

我试图在 swift 中创建字典,但出现错误。我尝试通过添加“?”来展开变量。不确定创建字典的正确方法是什么

class Event: NSObject { 
 
// When I remove the '?' on the variables it works but im not quite sure why 
// Should I not be declaring variable as optional unwrapped? 
 
var title:String? 
var eventDescription:String? 
var duration:Double? 
var eventID:String? 
var hostID:String? 
var location:CLLocation? 
var category:String? 
var invitedUsers:[String?] 
 
func createEvent(){ 
 
    // setting up event information to save 
    var postEventData = [ 
        "title": self.title, 
        "description":self.eventDescription, 
        "duration":self.duration, 
        "host":self.hostID, 
        "category":self.category 
    ] 
 
} 
func setTitle(title:String?){ 
    self.title = title 
} 
 
func setEventDescription(eventDescription:String?){ 
    self.eventDescription = eventDescription 
} 
 ..... 
} 

请您参考如下方法:

这里你说title(和其他属性)可能有也可能没有值:

var title:String? 

然后在这里你尝试使用title的值:

var postEventData = [ 
    "title": self.title, 
    "description":self.eventDescription, 
    "duration":self.duration, 
    "host":self.hostID, 
    "category":self.category 
] 

如果 title 没有值,您需要决定要做什么。应该创建 postEventData 吗?它应该使用默认值吗?理论上您可以创建一个 [String : String?] 的字典,但这通常没有用(因为从字典中获取值已经返回一个可选值)。

因此,根据您对该数据结构的需求,这里有多种选择。

  • 使您的属性成为非可选的。这些属性没有值(value)真的可以吗?也许它们应该默认为 "" 而不是可选的。

  • 只有在设置了所有属性时才允许 createEvent()(我重写了 createEvent 以返回一个值,因为您当前的代码只是创建了一个变量并且然后把它扔掉,所以我不确定目标是什么):


func createEvent() -> [String: String] { 
    if let title = self.title, 
           description = self.eventDescription, 
           duration = self.duration,  
           host = self.hostID, 
           category = self.category { 
        return [ 
            "title": title, 
            "description": description, 
            "duration": duration, 
            "host": host, 
            "category": category 
         ] 
     } 
     return nil 
 } 

  • 如果未设置属性,则使用默认值:

func createEvent() -> [String: String] { 
    return [ 
        "title": self.title ?? "",  
        "description": self.eventDescription ?? "", 
        "duration": self.duration ?? "", 
        "host": self.hostID ?? "", 
        "category": self.category ?? "" 
    ] 
} 
  • 或者问问自己为什么要创建字典。你已经有了一个数据结构;你真的需要转换它吗?

作为旁注,您的 set... 方法没有任何理由。 set 的前缀在 Swift 中有特殊的含义。调用者应该只说 event.title = ...。如果您需要某种特殊的 setter 处理,请使用 set 选项在您的属性上定义它。