[英]How to convert this ObjC code to swift3?
I am converting my ObjC code to Swift and stucking on this code. 我将我的ObjC代码转换为Swift并停留在该代码上。
for (id<Delegate> object in Objects)
{
.......
......
}
Any help would be greatly appreciated!. 任何帮助将不胜感激!。
Thanks. 谢谢。
You can do something like this 你可以做这样的事情
for object in Objects {
guard let delegateObject = object as? Delegate else {
continue
}
// rest of your loop here
}
Your Objective-C syntax is saying that you have a collection, called Objects
, for which the objects conform to some protocol called Delegate
. 您的Objective-C语法是说您有一个名为
Objects
的集合,其对象符合称为Delegate
某种协议。 The syntax in Swift is the largely the same: Swift中的语法大致相同:
func callDelegateMethod(for objects: [Delegate]) {
for object in objects {
object.someDelegateMethod()
}
}
Or 要么
func callDelegateMethod(for objects: [Delegate]) {
objects.forEach { object in
object.someDelegateMethod()
}
}
Note, in those examples, I broadened the example to show how objects
was declared (ie as an array of objects that conform to Delegate
protocol). 注意,在这些示例中,我扩大了示例以显示如何声明
objects
(即,作为符合Delegate
协议的对象数组)。
If your objects
array was something more ambiguous, something for which the conformance to Delegate
couldn't be determined at compile-time, (eg an an array of Any
, or what have you), you might need to cast it. 如果您的
objects
数组比较含糊,而在编译时无法确定是否符合Delegate
(例如, Any
或您拥有的数组),则可能需要强制转换。 For example, if you know that everything in objects
will conform to Delegate
, you could do: 例如,如果您知道
objects
中的所有内容都将符合Delegate
,则可以执行以下操作:
for object in objects as! [Delegate] {
object.someDelegateMethod()
}
But, as!
但是,
as!
can be dangerous, as it will crash if any of those casts fail. 可能很危险,因为如果其中任何一个强制失败,它都会崩溃。 So if there is any possibility that any of the objects might not conform, you would optionally cast, eg
因此,如果有任何对象可能不符合的可能性,则可以选择强制转换,例如
for object in objects {
if let object = object as? Delegate {
object.someDelegateMethod()
}
}
Or, writing that using functional methods like compactMap
(previously called flatMap
in Xcode versions prior to 9.3) and forEach
: 或者,使用诸如
compactMap
(在9.3之前的Xcode版本中以前称为flatMap
)和forEach
类的功能方法来编写该代码:
objects.flatMap { $0 as? Delegate } // use `compactMap` in Xcode 9.3 and later
.forEach { object in
object.someDelegateMethod()
}
There are two possible options. 有两种可能的选择。
Paste your code in any online converters like Swiftify . 将您的代码粘贴到任何在线转换器(如Swiftify)中 。
Edit-> Convert-> To modern swift code
Then you will get almost exact swift 2.2 or 3 code. 然后,您将获得几乎准确的2.2或3代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.