如何使用构造函数将自定义类型转换为数组?
extension Array where Generator.Element == Int{ // same-type requirement makes generic parameter 'Element' non-generic
// `where Element: SignedIntegerType` would work but that is a protocol
init(_ value:Custom){
self = [value.item1, value.item2, value.item3, value.item4 ] // cannot assign value of type '[Int]' to type 'Array<_>'
}
}
struct Custom{
// let array = [item.........] I could also have an array here but that is not the point of the question.
private let item1:Int
private let item2:Int
private let item3:Int
private let item4:Int
init(_ value1:Int, _ value2:Int, _ value3:Int, _ value4:Int ){
self.item1 = value1
self.item2 = value2
self.item3 = value3
self.item4 = value4
}
}
let custom = Array(Custom(2, 3, 4, 5))// I want to be be able to convert to an array/set.
编辑:我认为这可能是 swift 2.1 的限制
最佳答案
带有自定义类型的 Swift 3 示例:
假设您将 MyCustomType 作为自定义类:
class MyCustomType
{
var name = ""
var code = ""
convenience init(name: String, code: String)
{
self.init()
self.name = name
self.code = code
}
}
你可以这样扩展数组:
extension Collection where Iterator.Element == MyCustomType
{
func getNameFrom(code: String) -> String?
{
for custom in self {
if custom.code == code {
return custom.name
}
}
return nil
}
}
用法:
let myCustomArray = [MyCustomType]()
myCustomArray.getNameFrom(code: "code")
希望对您有所帮助! :)
关于arrays - 自定义类型的数组初始值设定项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34917365/