[swift-users] for with optional collection?

Rick Mann rmann at latencyzero.com
Thu Feb 9 16:48:13 CST 2017


> On Feb 9, 2017, at 13:31 , Saagar Jha <saagar at saagarjha.com> wrote:
> 
> for item in someOptionalCollection ?? [] {
> 	item.doSomething()
> }
> 

Thanks, this is probably the closest. Sadly I can't seem to test downcasting because Playgrounds just stop working, with no feedback, for this code:

class Foo
{
	init(_ inVal: String) { self.name = inVal }
	
	var name: String
	var desc: String { get { return "Foo \(name)" } }
}

let f = Foo("foo")

class Bar : Foo
{
	var desc: { return "Bar \(name)" }
}

let stuff: [Foo]?// = [Bar("foo"), Bar("bar"), Bar("baz")]
for item in (stuff as? [Bar]) ?? []
{
}

-- 
Rick Mann
rmann at latencyzero.com




More information about the swift-users mailing list