Hey everyone,
I'm playing with using Apple's legacy types with Swift and discovered an interesting conundrum:
- At some point in my code I'm using API which provides me with
CFArray
. I use it as follows:
let attachments: NSArray! =
CMSampleBufferGetSampleAttachmentsArray(
sampleBuffer!,
createIfNecessary: true
)
- Now, I happen to know that first element of this
CFArray
is aCFMutableDictionary
. I modify it as follows:
let dictionary = unsafeBitCast(CFArrayGetValueAtIndex(attachments, 0),
to: CFMutableDictionary.self)
let key = Unmanaged.passUnretained(
kCMSampleAttachmentKey_DisplayImmediately).toOpaque()
let value = Unmanaged.passUnretained(kCFBooleanTrue).toOpaque()
CFDictionarySetValue(dictionary, key, value)
- For debugging purposes, I created the following variables after the modification:
var isItNsMutableDictionary = attachments[0] is NSMutableDictionary
var maybeNsMutableDictionary = attachments[0] as? NSMutableDictionary
var nsMutableDictionary = maybeNsMutableDictionary!
var nsMutableDictionaryForcedDowncast =
attachments[0] as! NSMutableDictionary
- I attached debugger to look at variables. Here is what it said:
(lldb) po isItNsMutableDictionary
true
(lldb) po maybeNsMutableDictionary
▿ Optional<NSMutableDictionary>
▿ some : 1 element
▿ 0 : 2 elements
- key : DisplayImmediately
- value : 1
(lldb) po nsMutableDictionary
▿ 1 element
▿ 0 : 2 elements
- key : DisplayImmediately
- value : 1
(lldb) po nsMutableDictionaryForcedDowncast
<uninitialized>
What's going on there?
- Why is
nsMutableDictionaryForcedDowncast
different thennsMutableDictionary
?- I expected
(a as? NSMutableDictionary)!
to be the same asa as! NSMutableDictionary
- I expected
- What could be the reason
as?
works correctly whenas!
don't? Which one should I use?