Swift新特性整理

前端之家收集整理的这篇文章主要介绍了Swift新特性整理前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
 
 

编译警告

运行时警告会打印在控制台:

***Swift runtime: 
ClassName.swift:lineInFile:columnInLine: 
entrypoint -[ClassName methodName] generated by implicit @objc inference is deprecated and will be removed in Swift 4; 
add explicit @objc to the declaration to emit the Objective-C entrypoint in Swift 4 and suppress this message

同样:想要修复运行时警告,需要添加 @objc 修饰符到对应的方法或者符号。

运行时警告的常见原因:

  • 在 OC 中使用 SEL
  • 在 swift 中使用了 perform methods
  • 在 OC 中使用了 performSelector methods
  • 使用了 @IBOutlet 或者 @IBAction

其他修改

@H_404_30@NSAttributedStringKey
swift3.x
public init(string str: String,attributes attrs: [AnyHashable : Any]? = nil)

swift4.0
public init(string str: String,attributes attrs: [NSAttributedStringKey : Any]? = nil)
@H_404_30@String

废弃characters

swift 3
var count = string.characters.count

error
'characters' is deprecated: Please use String or Substring directly

swift 4
count = string.count

废弃addingPercentEscapes

swift 3
var url = @"http://www.example.com?username=姓名"
url = url.addingPercentEscapes(using: String.Encoding.utf8)!

error
'addingPercentEscapes(using:)' is unavailable: Use addingPercentEncoding(withAllowedCharacters:) instead,which always uses the recommended UTF-8 encoding,and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.

swift 4
uri = uri.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

废弃substring(to:)

swift 3
let index = tagText.index(tagText.startIndex,offsetBy: MPMultipleStyleListItemTagMaxLength)

// 警告:'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range upto' operator.
let b = tagText.substring(to: index)

Swift 4
let a = tagText.prefix(upTo: index) //a 的类型是 Substring,不是 String

pod 引用

添加以下内容到 Podfile

post_install do |installer|
    installer.pods_project.targets.each do |target|
        if ['WTCarouselFlowLayout','XSLRevenue','OHHTTPStubs/Swift'].include? target.name
            target.build_configurations.each do |config|
                config.build_settings['SWIFT_VERSION'] = '3.2'
            end
        end
    end
end

系统方法

UITableViewDelegate 协议方法名变更,没有错误提示

// swift3.x
func tableView(_ tableView: UITableView,heightForRowAtIndexPath indexPath: IndexPath) -> CGFloat 

// swift4.0
func tableView(_ tableView: UITableView,heightForRowAt indexPath: IndexPath) -> CGFloat

猜你在找的Swift相关文章