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

其他修改

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)

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

相关文章

软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘...
现实生活中,我们听到的声音都是时间连续的,我们称为这种信...
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿...
【Android App】实战项目之仿抖音的短视频分享App(附源码和...
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至...
因为我既对接过session、cookie,也对接过JWT,今年因为工作...