Swift 2.0:'枚举'不可用:拨打' enumerate()'序列上的方法

时间:2015-06-09 11:11:41

标签: swift swift2

刚刚下载了Xcode 7 Beta,此错误出现在enumerate关键字上。

for (index, string) in enumerate(mySwiftStringArray)
{

}

任何人都可以帮助我克服这个问题吗?

此外,似乎count()不再用于计算String的长度。

let stringLength = count(myString)

在上面一行,编译器说:

  

'计数'不可用:访问'计数'该集合的财产。

Apple是否已发布任何Swift 2.0编程指南?

3 个答案:

答案 0 :(得分:105)

许多全局函数已被协议扩展方法取代, Swift 2的一个新功能,因此enumerate()现在是一种扩展方法 SequenceType

extension SequenceType {
    func enumerate() -> EnumerateSequence<Self>
}

并用作

let mySwiftStringArray = [ "foo", "bar" ]
for (index, string) in mySwiftStringArray.enumerate() {
   print(string) 
}

String不再符合SequenceType,你必须这样做 使用characters属性获取Unicode集合 字符。此外,count()是协议扩展方法 CollectionType而不是全局函数:

let myString = "foo"
let stringLength = myString.characters.count
print(stringLength)

Swift 3更新: enumerate()已重命名为enumerated()

let mySwiftStringArray = [ "foo", "bar" ]
for (index, string) in mySwiftStringArray.enumerated() {
    print(string)
}

答案 1 :(得分:5)

使用enumerate()时,Swift 2有了更新。

人们应该使用

而不是[Register ("MyViewController")] partial class MyViewController { [Outlet] public UITableView myTableView { get; set; } // ... } public partial class MyViewController : UIViewController { public UIRefreshControl myRefreshControl { get; set; } public override void ViewDidLoad() { base.ViewDidLoad(); // ... this.myRefreshControl = new UIRefreshControl(); this.myRefreshControl.AttributedTitle = new NSAttributedString("Load News from server..."); this.myRefreshControl.AddTarget(this, new ObjCRuntime.Selector("RefreshSource"), UIControlEvent.ValueChanged); #region Fix the Jump problem UITableViewController tableViewController = new UITableViewController(); tableViewController.TableView = this.myTableView; tableViewController.RefreshControl = this.myRefreshControl; #endregion #region Fix the unwanted first showing this.myRefreshControl.BeginRefreshing(); this.myRefreshControl.EndRefreshing(); #endregion // ... } [Export("RefreshSource")] private async void RefreshSource() { #region Edit source data await Task.Run(() => { Thread.Sleep(3000); }); #endregion this.myTableView.ReloadData(); this.myRefreshControl.EndRefreshing(); } }

... enumerate(...)

原因是许多全局函数已被协议扩展方法取代,它们将获得枚举错误。

希望这会有所帮助。 祝一切顺利。 Ñ

答案 2 :(得分:0)

我知道这是一个老线程,但我一直在搞乱Swift 2.0和Playgrounds,我遇到了同样的问题,我认为我共享一个使用enumerate()方法的解决方案一个字符串

// This line works in Swift 1.2
// for (idx, character) in enumerate("A random string, it has a comma.")

// Swift 2.x
let count = inputString.characters

for (idx, character) in count.enumerate() where character == "," {

    // Do something with idx
}

希望这有帮助

由于 启

相关问题