可选的绑定和引用

时间:2014-11-10 10:29:10

标签: swift

我可以以某种方式使用可选绑定作为引用吗?如果是,我该怎么做?

以下代码对self.threadsInfo?.threads?的副本进行排序,而不是原始副本。

if var threads = self.threadsInfo?.threads? {
            switch self.threadsSortType
            {
            case .Score:
                threads.sort {
                    $0.score > $1.score
                }
            case .Views:
                threads.sort {
                    $0.views > $1.views
                }
            case .PostsCount:
                threads.sort {
                    $0.postsCount > $1.postsCount
                }
            default:
                assert(false, "Unknown threads sort type")
            }
        }

提前致谢。

2 个答案:

答案 0 :(得分:3)

数组是值类型,因此将其复制到此处:

var threads = self.threadsInfo?.threads?

您可以将已排序的数组分配回原始数据:

if var threads = self.threadsInfo?.threads? {
            switch self.threadsSortType
            {
            case .Score:
                threads.sort {
                    $0.score > $1.score
                }
            case .Views:
                threads.sort {
                    $0.views > $1.views
                }
            case .PostsCount:
                threads.sort {
                    $0.postsCount > $1.postsCount
                }
            default:
                assert(false, "Unknown threads sort type")
            }

            self.threadsInfo?.threads = threads
        }

答案 1 :(得分:3)

您可以通过引用将排序逻辑移动到接受非可选数组的单独函数中:

func sort(inout threads: [MyThreadType]) {
    switch self.threadsSortType {
    case .Score:
        threads.sort {
            $0.score > $1.score
        }

    case .Views:
        threads.sort {
            $0.views > $1.views
        }

    case .PostsCount:
        threads.sort {
            $0.postsCount > $1.postsCount
        }

    default:
        assert(false, "Unknown threads sort type")
    }
}

并致电:

if self.threadsInfo?.threads != nil {
    sort(&self.threadsInfo!.threads!)
}

值类型总是按值传递(即通过复制)。它们可以通过引用传递的唯一情况是通过inout修饰符函数/方法。