xcode - Swift:具有 "for in loop",其中范围由 return 语句确定

标签 xcode swift

我正在构建一个自定义 UI,但我意识到由于某种原因我无法做到这一点。

protocol notImportant{
   SegementButtons(segmentControl : VerticalSegmentControl) -> Int
}
 //trying to use the function later in this fashion below

for index in 0...delegate?.segementButtonsCount(self)

现在我知道还有很多其他解决方案。

首先,这是有效的还是我必须提供具体的数字或变量?

继续

Xcode 显示错误

        Binary operator '...' cannt be applied to oraands of type Int and Int?

我将返回值转换为 Int,将错误更改为

        Type Int does not conform to protocol SequenceType

现在,如果我能在 Xcode 不 self 切割的情况下完成这项工作,那就太酷了。

最佳答案

delegate是可选的,因此表达式的类型

delegate?.segmentButtonsCount(self)

也是可选的(如果 nil 则为 delegate == nil )。

您可以使用可选绑定(bind)来解开委托(delegate)

if let theDelegate = delegate {
     for index in 0 ..< theDelegate.segmentButtonsCount(self) {
         // do something ...
     }
}

或使用零合并运算符 ??提供一个 默认值:

 for index in 0 ..< (delegate?.segmentButtonsCount(self) ?? 0) {
     // do something ...
 }

请注意,由于数组索引是从零开始的,因此您可能需要使用范围运算符 ..<哪个 排除结束元素。

关于xcode - Swift:具有 "for in loop",其中范围由 return 语句确定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29764167/

相关文章:

ios - iOS 开发中是否存在与 Android 产品风格等效的概念?

ios - 连接 Outlet Collection 故障

ios - 如何在 swift ios 中调整 Collection View 单元格高度?

ios - Swift FIRMessaging 推送通知 token 重置

ios - 将 MP3 添加到应用程序主包而不更新

ios - 错误: ITMS-90034: Missing or invalid signature is not signed using an Apple submission certificate

ios - UIImage imageNamed 返回 nil

c++ - 从后台线程错误修改自动布局引擎,来自 C++

Swift 泛型 : parameters cyclic dependencies resolution

xcode - Swift 显示从 prepareForSegue 传递的数据