I\'m moving from swift 3 to swift 4. I have UILabels that I am giving very specific text properties to the label. I\'m getting an \'unexpectedly found nil while unwrapping
In Swift 4.0+
, attributed string accepts json (dictionary) with key type NSAttributedStringKey
or NSAttributedString.Key
.
So you must change it from [String : Any]
to
Swift 4.1 & below - [NSAttributedStringKey : Any]
&
Swift 4.2 & above - [NSAttributedString.Key : Any]
Initialiser for AttributedString
in Swift 4.2 is changed to [NSAttributedString.Key : Any]?
public init(string str: String, attributes attrs: [NSAttributedString.Key : Any]? = nil)
Here is sample working code.
let label = UILabel()
let labelText = "String Text"
let strokeTextAttributes = [
NSAttributedString.Key.strokeColor : UIColor.black,
NSAttributedString.Key.foregroundColor : UIColor.white,
NSAttributedString.Key.strokeWidth : -2.0,
NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 18)
] as [NSAttributedString.Key : Any]
label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)
Initialiser for AttributedString
in Swift 4.0 is changed to [NSAttributedStringKey : Any]?
.
public init(string str: String, attributes attrs: [NSAttributedStringKey : Any]? = nil)
Here is sample working code.
let label = UILabel()
let labelText = "String Text"
let strokeTextAttributes = [
NSAttributedStringKey.strokeColor : UIColor.black,
NSAttributedStringKey.foregroundColor : UIColor.white,
NSAttributedStringKey.strokeWidth : -2.0,
NSAttributedStringKey.font : UIFont.boldSystemFont(ofSize: 18)
] as [NSAttributedStringKey : Any]
label.attributedText = NSAttributedString(string: labelText, attributes: strokeTextAttributes)
Look at this Apple Document, for more info: NSAttributedString - Creating an NSAttributedString Object