- Swift Functional Programming(Second Edition)
- Dr. Fatih Nayebi
- 167字
- 2021-07-02 23:54:20
Modern syntax
Swift has a modern syntax that eliminates the verbosity of programming languages such as Objective-C. For instance, the following code example shows an Objective-C class with a property and method. Objective-C classes are defined in two separate files (interface and implementation). The VerboseClass.h file defines an interface as a subclass of the NSObject class. It defines a property, ourArray, and a method, aMethod.
The implementation file imports the header class and provides an implementation for aMethod, as shown in the following code:
// VerboseClass.h
@interface VerboseClass: NSObject
@property (nonatomic, strong) NSMutableArray *ourArray;
- (void)aMethod:(NSMutableArray*)anArray;
@end
// VerboseClass.m
#import "VerboseClass.h"
@implementation VerboseClass
- (void)aMethod:(NSMutableArray*)anArray {
self.ourArray = [[NSMutableArrayalloc] initWithArray: @[@"One",
@"Two", @"Three"]];
}
A similar functionality in Swift can be achieved as follows:
class ASwiftClass {
var ourArray: [String] = []
func aMethod(anArray: [String]) {
self.ourArray = anArray
}
}
let aSwiftClassInstance = ASwiftClass()
aSwiftClassInstance.aMethod(anArray: ["one", "Two", "Three"])
print(aSwiftClassInstance.ourArray)
As seen from this example, Swift eliminates a lot of unnecessary syntax and keeps code very clean and readable.
推薦閱讀
- Access 2016數據庫教程(微課版·第2版)
- SQL Server 2012數據庫技術與應用(微課版)
- Modern Programming: Object Oriented Programming and Best Practices
- 正則表達式必知必會
- 數據結構與算法(C語言版)
- UDK iOS Game Development Beginner's Guide
- 智能數據分析:入門、實戰與平臺構建
- 一個64位操作系統的設計與實現
- 白話大數據與機器學習
- 高維數據分析預處理技術
- Python 3爬蟲、數據清洗與可視化實戰
- PostgreSQL高可用實戰
- AndEngine for Android Game Development Cookbook
- Visual Studio 2012 and .NET 4.5 Expert Development Cookbook
- 云原生架構:從技術演進到最佳實踐