为啥这个元组在 swift 3 中没有更多上下文就模棱两可?
Posted
技术标签:
【中文标题】为啥这个元组在 swift 3 中没有更多上下文就模棱两可?【英文标题】:Why is this tuple ambiguous without more context in swift 3?为什么这个元组在 swift 3 中没有更多上下文就模棱两可? 【发布时间】:2016-06-24 19:07:50 【问题描述】:在查看了几个月前有效的代码后,能否解释一下如何修复此错误?显示的错误是“表达式类型不明确,没有更多上下文”。
var products = [("Kayak","A boat for one person","Watersports",275.0,10),
("Lifejacket","Protective and fashionable","Watersports",48.95,14),
("Soccer Ball","FIFA-approved size and weight","Soccer",19.5,32),
("Corner Flags","Give your playing field a professional touch","Soccer",34.95,1),
("Stadium","Flat-packed 35,000-seat stadium","Soccer",79500.0,4),
("Improve your brain efficiency by 75%","Chess",16.0,8),
("Unsteady Chair","Secretly give your opponent a disadvantage","Chess",29.95,3),
("Human Chess Board","A fun game for the family","Chess",75.0,2),
("Bling-Bling King","Gold-plated,diamon-studded King","Chess",1200.0,4)]
【问题讨论】:
查找“奇怪错误信息”原因的常用程序是删除行直到问题消失,然后重新添加行,以隔离问题。你可以自己轻松地做到这一点...... 当内置类型推断失败时,我更喜欢明确说明类型并查看错误是否消失。如果不是,则很好地证明该类型实际上并不模棱两可,而是完全错误(或者至少不是您认为的那样)。 善待你的编译器。不要在不告诉它类型的情况下给它很大的初始值:var products: [(String, String, String, Double, Int)] = [...
。如果你这样做了,它会告诉你error: cannot convert value of type '(String, String, Double, Int)' to expected element type '(String, String, String, Double, Int)'
并指出问题所在。
【参考方案1】:
这一行:
("Improve your brain efficiency by 75%","Chess",16.0,8),
只有 2 个字符串而不是 3 个。活动名称 (?) 似乎丢失了。
【讨论】:
【参考方案2】:不要像这样滥用结构。您应该将其重构为结构:
struct Product //fill these names in better
let name: String
let description: String
let category: String
let price: Double
let x: Int
var products = [
Product(name: "Kayak",
description: "A boat for one person",
category: "Watersports", price: 275.0, x: 10),
Product(name: "Lifejacket",
description: "Protective and fashionable",
category: "Watersports", price: 48.95, x: 14),
Product(name: "Soccer Ball",
description: "FIFA-approved size and weight",
category: "Soccer", price: 19.5, x: 32),
Product(name: "Corner Flags",
description: "Give your playing field a professional touch",
category: "Soccer", price: 34.95, x: 1),
Product(name: "Stadium",
description: "Flat-packed 35,000-seat stadium",
category: "Soccer", price: 79500.0, x: 4),
Product(name: "YOU FORGOT TO GIVE ME A NAME",
description: "Improve your brain efficiency by 75%",
category: "Chess", price: 16.0, x: 8),
Product(name: "Unsteady Chair",
description: "Secretly give your opponent a disadvantage",
category: "Chess", price: 29.95, x: 3),
Product(name: "Human Chess Board",
description: "A fun game for the family",
category: "Chess", price: 75.0, x: 2),
Product(name: "Bling-Bling King",
description: "Gold-plated,diamon-studded King",
category: "Chess", price: 1200.0, x: 4)
]
这使得所有这些值的含义更加清晰,并且使访问它们更加自然(例如,您可以通过product.name
而不是product.1
获取名称)。
【讨论】:
以上是关于为啥这个元组在 swift 3 中没有更多上下文就模棱两可?的主要内容,如果未能解决你的问题,请参考以下文章
为啥列表有 __reverse__() 特殊方法但元组在 Python 中没有?