Swift中的数据封装 [英] Data encapsulation in Swift

查看:92
本文介绍了Swift中的数据封装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了整本速成书,并观看了所有 WWDC视频(我衷心推荐所有这些视频)。我担心的一件事是数据封装。



请考虑以下示例(完全人为设计):

  class Stack< T> 
{
var个项:T [] = []

func push(newItem:T){
items.insert(newItem,atIndex:0)
}

func pop()-> T? {
如果items.count == 0 {
返回nil;
}

return items.removeAtIndex(0);
}
}

此类实现了一个堆栈,并使用一个数组。问题是, items (就像Swift中的所有属性一样)是公共的,因此没有什么可以阻止任何人直接从公共API单独访问(甚至对其进行突变)。作为一个只有curmudge的C ++老家伙,这让我非常脾气暴躁。我听说有传言称它们可能会很快实现,我想知道如果没有它们,将会有什么隐藏数据的策略。



我错过了什么吗,或者这仅仅是语言上的遗漏?

解决方案

目前暂时不存在。格雷格·帕克(Greg Parker)在此开发论坛主题中明确声明( ),可见性修饰符即将到来。



鉴于没有标头,标准的Objective-C技巧将不起作用,而且我想不出另一种限制可视性的技巧,该技巧不涉及很多向后弯腰。由于已经承诺要使用语言功能,因此我不确定它是否值得进行任何大的投资。



从好的方面来说,由于该功能 不断变化,现在是提交雷达并影响结果的好时机。


I've read the entire Swift book, and watched all the WWDC videos (all of which I heartily recommend). One thing I'm worried about is data encapsulation.

Consider the following (entirely contrived) example:

class Stack<T>
{
    var items : T[] = []

    func push( newItem: T ) {
        items.insert( newItem, atIndex: 0 )
    }

    func pop() -> T? {
        if items.count == 0 {
            return nil;
        }

        return items.removeAtIndex( 0 );
    }
}

This class implements a stack, and implements it using an Array. Problem is, items (like all properties in Swift) is public, so nothing is preventing anyone from directly accessing (or even mutating) it separate from the public API. As a curmudgeonly old C++ guy, this makes me very grumpy.

I see people bemoaning the lack of access modifiers, and while I agree they would directly address the issue (and I hear rumors that they might be implemented Soon (TM) ), I wonder what some strategies for data hiding would be in their absence.

Have I missed something, or is this simply an omission in the language?

解决方案

It's simply missing at the moment. Greg Parker has explicitly stated (in this dev forums thread) that visibility modifiers are coming.

Given that there aren't headers, the standard Objective-C tricks won't work, and I can't think of another trick to limit visibility that doesn't involve lots of bending over backwards. Since the language feature has been promised I'm not sure it's worth any big investment.

On the bright side since this feature is in flux, now is a great time to file a radar and influence how it turns out.

这篇关于Swift中的数据封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆