iT邦幫忙

第 12 屆 iThome 鐵人賽

DAY 25
0
Mobile Development

30 天從 Swift 學會 Objective-C系列 第 25

[25] 30 天從 Swift 學會 Objective-C:Swift friendly 的 Optional

Swift 的 optional 是一個很有趣的概念,因為在 Objective-C 與 C 語言,相關的概念是使用 0 代稱。

複習 Swift 的 Optional syntax

在開始了解之前,我們先複習以下 Swift Optionals - Swift.org
我們要了解的目標是 MyClass?MyClass!

處理 C 語言的 Pointer NULL

我們知道 Class 在 C 語言是 Pointer,而 Pointer 為了提供記憶體管理使得 Pointer 是可以為 NULL,在 Swift 因為 ARC 的關係而可以使用

在我們透過 Xcode 建立一個 Cocoa Touch class 時,Xcode 給了我們一個 template file,這個 template 檔案內建有 NS_ASSUME_NONNULL_BEGINNS_ASSUME_NONNULL_END

這兩個代表在其行數間的物件如果沒有其他定義,則預設不可以有 NULL Pointer。

Class? 與 Class!

imports into Swift as Methods and properties Any Pointer
MyClass nonnull _Nonnull
MyClass? nullable _Nullable
MyClass! null_unspecified _Null_unspecified

表格來自 WWDC 2020 - Refine Objective-C frameworks for Swift

nullable 與 null_unspecified 作用域是在 properties 與 Methods

// Objective-C
/* Atemplate.h */
NS_ASSUME_NONNULL_BEGIN
@interface ATemplate: NSObject
@property(nullable) aNullableProperty;
-(nonull instan)
-(nonnull instancetype) initWithName(nullable NSString*)name;
@end
NS_ASSUME_NONNULL_END
// Swift interface
import Foundation

open class Atemplate : NSObject {

    open var aNullableProperty: NSNumber?

    public init(name: String?)
}

而全域變數或是 Any(id),

NSString* _Nonnull  NoneNullString = @"";
// Swift interface
public let NoneNullString: String
@interface Atemplate: NSObject
...
-(BOOL) resource:(id _Nullable * _Nonnull)outValue;
@end
class Atemplate{
    ...
    open func resource(_ outValue: AutoreleasingUnsafeMutablePointer<AnyObject?>) -> Bool
}

簡單測驗

  1. 請說明使用 MYClass! 的時機是什麼?
  2. [進階] 請說明 (id _Nullable * _Nonnull) 的意思是什麼? 其所對應 Swift 的 AutoreleasingUnsafeMutablePointer 是什麼?

上一篇
[24] 30 天從 Swift 學會 Objective-C:Swift friendly 的 泛型
下一篇
[26] 30 天從 Swift 學會 Objective-C:Swift friendly 的 Error handling
系列文
30 天從 Swift 學會 Objective-C30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言