LoginSignup
9
5

More than 5 years have passed since last update.

Swift 4.0でNSAttributedStringの装飾属性Dictionaryがエラーになる件

Posted at

以前は以下のようなコードでコンパイルできましたが、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)
]
9
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
5