BostonMacOSX BostonMacOSX - 1 month ago 6
Swift Question

I'm unable to enumerate an NSAttributed Text in Swift 3

I'm unable to get this to compile correctly in swift 3. I'm running into the issue of

enter image description here

Actual code here. i'm not sure why it is asking for an extra , in the code

data2 = items.data(using: .utf8)
attrString = NSAttributedString(htmlData:data2!,options:[DTDefaultFontSize:13.0,DTDefaultFontFamily:"Verdana",DTDefaultFirstLineHeadIndent:5.0],documentAttributes:nil)
print(attrString)

attrString?.enumerateAttribute(NSAttachmentAttributeName , in: NSMakeRange(0, (attrString?.length)!), options: 0, using:^(id value,NSRange range,BOOL *test){
if(value){
print(value)
}
})

Answer

You must have copied an Objective C example without converting it fully to swift. Things like the block syntax and the if(value) are valid objective C but not valid swift. The following code works correctly in a Swift playground:

    let attrString = NSAttributedString(string: "test", attributes: [NSForegroundColorAttributeName : UIColor.red, NSUnderlineColorAttributeName : UIColor.green])
    attrString.enumerateAttribute(NSForegroundColorAttributeName , in: NSMakeRange(0, attrString.length), options: [.longestEffectiveRangeNotRequired]) { value, range, isStop in
        if let value = value {
            print(value)
        }
    }
Comments