我有这样的数据模型
struct Aboutme {
private(set) public var name: String
init(name: String) {
self.name = name
}
}
像这样的数据服务
struct DataService {
static let instance = DataService()
private let sections = [
[Aboutme(name: "Rate App on the App store")],
[Aboutme(name: "Facebook")],
[Aboutme(name: "Twitter")],
[Aboutme(name: "Linkeden")],
[Aboutme(name: "Instagram")],
[Aboutme(name: "Email Feedback")]
]
func getSections() -> [Aboutme] {
return sections
}
}
然而,当我尝试返回关于我的类型的部分,它不会让我,说我不能将返回表达式转换为另一个。我怎样才能解决这个问题。
答案 0 :(得分:3)
sections
(隐式)声明为[[Aboutme]]
getSections()
的返回值为[Aboutme]
,这是经典类型不匹配。
解决方案:
更改sections
struct DataService {
static let instance = DataService()
private let sections = [
Aboutme(name: "Rate App on the App store"),
Aboutme(name: "Facebook"),
Aboutme(name: "Twitter"),
Aboutme(name: "Linkeden"),
Aboutme(name: "Instagram"),
Aboutme(name: "Email Feedback")
]
func getSections() -> [Aboutme] {
return sections
}
}
更改getSections()
struct DataService {
static let instance = DataService()
private let sections = [
[Aboutme(name: "Rate App on the App store")],
[Aboutme(name: "Facebook")],
[Aboutme(name: "Twitter")],
[Aboutme(name: "Linkeden")],
[Aboutme(name: "Instagram")],
[Aboutme(name: "Email Feedback")]
]
func getSections() -> [[Aboutme]] {
return sections
}
}
因为sections
是常量,函数getSections()
是多余的,根本不需要。
为什么不简单
struct Aboutme {
let name: String
}
您可以免费获得初始化程序,name
是预期的常量。
答案 1 :(得分:1)
您的sections
跟随数组集合,因此您需要使用返回类型数组数组来返回所有[Aboutme]
个对象。
func getSections() -> [[Aboutme]] {
return sections
}
答案 2 :(得分:0)
问题是getSections
方法和变量sections
的返回类型是不同的类型。您必须更改var sections
类型,如getSections
方法返回类型或getSections
返回类型,如sections
。
所以你可以这样做:
struct DataService {
static let instance = DataService()
private let sections = [
Aboutme(name: "Rate App on the App store"),
Aboutme(name: "Facebook"),
Aboutme(name: "Twitter"),
Aboutme(name: "Linkeden"),
Aboutme(name: "Instagram"),
Aboutme(name: "Email Feedback")
]
func getSections() -> [Aboutme] {
return sections
}
}
或者像这样:
struct DataService {
static let instance = DataService()
private let sections = [
[Aboutme(name: "Rate App on the App store")],
[Aboutme(name: "Facebook")],
[Aboutme(name: "Twitter")],
[Aboutme(name: "Linkeden")],
[Aboutme(name: "Instagram")],
[Aboutme(name: "Email Feedback")]
]
func getSections() -> [[Aboutme]] {
return sections
}
}
答案 3 :(得分:0)
你的部分声明是错误的。您将段声明为数组数组(类型为Array<Array<Section>>
),因此当然不能将其转换为Array<Section>
。
struct DataService {
static let instance = DataService()
private let sections = [
Aboutme(name: "Rate App on the App store"),
Aboutme(name: "Facebook"),
Aboutme(name: "Twitter"),
Aboutme(name: "Linkeden"),
Aboutme(name: "Instagram"),
Aboutme(name: "Email Feedback")
]
func getSections() -> [Aboutme] {
return sections
}
}