arrays - 自定义类型的数组初始值设定项

标签 arrays swift swift2

如何使用构造函数将自定义类型转换为数组?

 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/

相关文章:

swift - SpriteKit 中的摩擦力

swift - 如何设置好UIScrollView

ios - 撤消模式并同时显示转场

java - 在一维数组中搜索

javascript - 使用映射更改内部数组对象值和外部数组值

ios - Swift:iOS 12.2 应用程序在启动时崩溃

swift - 调用可以抛出,但不能抛出全局变量初始值设定项之外的错误

ios - 由于未捕获的异常 'NSRangeException' 而终止应用程序,原因 : '*** -[__NSArray0 objectAtIndex:]

javascript - 迭代并获取字符串中每个由\n 分隔符分隔的值的元素,而不使用 split

c++ - 解压 C++ 指针/引用语法