以前は以下のようなコードでコンパイルできましたが、Swift 4ではコンパイルエラーになります。
let stringAttributes: [String : Any] = [
NSForegroundColorAttributeName : UIColor.blue,
NSFontAttributeName : UIFont.systemFont(ofSize: 24.0)
]
let string = NSAttributedString(string: "BlueString", attributes:stringAttributes)
label.attributedText = string
コンパイルエラーのメッセージ。
Cannot convert value of type 'NSAttributedStringKey' to expected dictionary key type 'String'
NSAttributesStringの属性キーは、NSAttributedStringKeyという型にしないとエラーになります。上記のような場合は、このようにします。
let stringAttributes: [NSAttributedStringKey : Any] = [
NSAttributedStringKey.foregroundColor : UIColor.blue,
NSAttributedStringKey.font : UIFont.systemFont(ofSize: 24.0)
]
さらに省略してこのようにも書けます。見やすいですね!
let stringAttributes: [NSAttributedStringKey : Any] = [
.foregroundColor : UIColor.blue,
.font : UIFont.systemFont(ofSize: 24.0)
]