NSObject无法转换

时间:2016-01-28 12:42:41

标签: ios swift

我在以下代码行中遇到错误。 由于这是我刚从github下载的项目,https://github.com/HubSpot/BidHub-iOS 我不确定这些线路在做什么。

  let one = NSMutableAttributedString(string: "BID\n", attributes: bidAttrs as [NSObject : AnyObject] as [NSObject : AnyObject] )
    one.appendAttributedString(NSMutableAttributedString(string: "$\(startAmount + incrementOne)", attributes: otherAttrs))
    plusOneButton.setAttributedTitle(one, forState: .Normal)

    let five = NSMutableAttributedString(string: "BID\n", attributes: bidAttrs as [NSObject : AnyObject] as [NSObject : AnyObject])
    five.appendAttributedString(NSMutableAttributedString(string: "$\(startAmount + incrementFive)", attributes: otherAttrs))
    plusFiveButton.setAttributedTitle(five, forState: .Normal)

    let ten = NSMutableAttributedString(string: "BID\n", attributes: bidAttrs as [NSObject : AnyObject] as [NSObject : AnyObject])
    ten.appendAttributedString(NSMutableAttributedString(string: "$\(startAmount + incrementTen)", attributes: otherAttrs))
    plusTenButton.setAttributedTitle(ten, forState: .Normal)

错误如下

/Users/David/Desktop/iOS_app/Bid-Hub-app/iOS-app/BidHub-iOS-master/AuctionApp/BiddingVC/BiddingViewController.swift:104:109: Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]?'
/Users/DAVID/Desktop/iOS_app/Bid-Hub-app/iOS-app/BidHub-iOS-master/AuctionApp/BiddingVC/BiddingViewController.swift:112:109: Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]?'
/Users/DAVID/Desktop/iOS_app/Bid-Hub-app/iOS-app/BidHub-iOS-master/AuctionApp/BiddingVC/BiddingViewController.swift:108:110: Cannot convert value of type '[NSObject : AnyObject]' to expected argument type '[String : AnyObject]?'

所以就在你建议我删除额外的

之前
as [NSObject : AnyObject]

已经尝试过,它会出现以下错误

/Users/David/Desktop/iOS_app/Bid-Hub-app/iOS-app/BidHub-iOS-master/AuctionApp/BiddingVC/BiddingViewController.swift:104:74: 'NSDictionary' is not implicitly convertible to '[NSObject : AnyObject]'; did you mean to use 'as' to explicitly convert?

编辑:

var bidAttrs = [NSFontAttributeName : UIFont(name: "Avenir-Light", size: 14.0)! , NSForegroundColorAttributeName: UIColor.grayColor()] as NSDictionary

1 个答案:

答案 0 :(得分:2)

您无需将bidAttrs投射到NSDictionary,所以只需执行此操作:

var bidAttrs = [NSFontAttributeName : UIFont(name: "Avenir-Light", size: 14.0)! , NSForegroundColorAttributeName: UIColor.grayColor()]
let one = NSMutableAttributedString(string: "BID\n", attributes: bidAttrs )

但是,如果由于某种原因需要它是NSDictionary,那么你的演员应该是这样的:

let one = NSMutableAttributedString(string: "BID\n", attributes: bidAttrs as? [String : AnyObject] )