Swift4中NSStoryboardSegue.Identifier?转String报错求助
解决Swift4中NSStoryboardSegue标识符类型不匹配的问题
这是Swift 4对NSStoryboardSegue.identifier类型做了调整导致的错误——原来Swift3里它是String?类型,到Swift4变成了NSStoryboardSegue.Identifier?,这是一个包装字符串的结构体,直接和字符串字面量比较自然会报类型不兼容的错误。下面给你几种可行的解决方案:
方案1:将字符串字面量转为Identifier类型比较
直接把你原来的字符串"segue"包装成NSStoryboardSegue.Identifier实例,就能和segue.identifier直接匹配了:
override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if segue.identifier == NSStoryboardSegue.Identifier("segue") { // 获取目标视图控制器的引用 let destinationVC: ProgressView = segue.destinationController as! ProgressView // 设置目标控制器的属性 destinationVC.fileArray = fileArray destinationVC.croptype = croptype destinationVC.outdir = outdir destinationVC.fileformat = fileformat destinationVC.tflag = tflag if resize == true { destinationVC.resize = true destinationVC.rwidth = rwidth destinationVC.rheight = rheight destinationVC.preserve_aspect_ratio = preserve_aspect_ratio } } }
方案2:使用Identifier的rawValue属性
NSStoryboardSegue.Identifier结构体自带一个rawValue属性,它的类型就是String,通过这个属性就能和你的字符串字面量做比较,改动最小:
override func prepare(for segue: NSStoryboardSegue, sender: Any?) { if segue.identifier?.rawValue == "segue" { // 原有代码逻辑完全不变 let destinationVC: ProgressView = segue.destinationController as! ProgressView destinationVC.fileArray = fileArray destinationVC.croptype = croptype destinationVC.outdir = outdir destinationVC.fileformat = fileformat destinationVC.tflag = tflag if resize == true { destinationVC.resize = true destinationVC.rwidth = rwidth destinationVC.rheight = rheight destinationVC.preserve_aspect_ratio = preserve_aspect_ratio } } }
方案3:更优雅的常量复用(推荐)
为了避免硬编码字符串带来的拼写错误,你可以给NSStoryboardSegue.Identifier写一个扩展定义常量,再用switch语句匹配,代码可读性和安全性都更高:
// 先扩展定义Segue标识符常量 extension NSStoryboardSegue.Identifier { static let toProgressView = NSStoryboardSegue.Identifier("segue") } override func prepare(for segue: NSStoryboardSegue, sender: Any?) { switch segue.identifier { case .toProgressView: let destinationVC: ProgressView = segue.destinationController as! ProgressView destinationVC.fileArray = fileArray destinationVC.croptype = croptype destinationVC.outdir = outdir destinationVC.fileformat = fileformat destinationVC.tflag = tflag if resize == true { destinationVC.resize = true destinationVC.rwidth = rwidth destinationVC.rheight = rheight destinationVC.preserve_aspect_ratio = preserve_aspect_ratio } default: // 处理其他segue或者直接跳过 break } }
这几种方法都能解决你的问题:如果想尽量贴近原有代码风格,方案2最省心;如果追求长期的代码可维护性,方案3是更优选择。
内容的提问来源于stack exchange,提问作者techno
相关产品推荐
相关产品推荐

