官术网_书友最值得收藏!

Objective-C and Swift comparison

Here's a quick review of our Swift code with a comparison to the Objective-C equivalent.

Objective-C

Here's a sample code in Objective-C:

const int MAX_ENEMIES = 10;  //constant
float playerPower = 1.3;     //variable

//Array of NSStrings
NSArray * stageNames = @[@"Downtown Tokyo", @"Heaven Valley", @" Nether"];

//Set of various NSObjects
NSSet *items = [NSSet setWithObjects: Weapons, Armor,
 HealingItems,"A", nil];

//Dictionary with an Int:String key:value
NSDictionary *inventory = [NSDictionary dictionaryWithObjectsAndKeys:
             [NSNumber numberWithInt:1], @"Buster Sword",
             [NSNumber numberWithInt:43], @"Potion",
             [NSNumber numberWithInt:22], @"Strength",
nil];

Swift

Here's the equivalent code in Swift:

let MAX_ENEMIES = 10          //constant
var playerPower = 1.3         //variable

//Array of Strings
let stageNames : [String] = ["Downtown Tokyo","Heaven Valley","Nether"]    

//Set of various NSObjects
var items = Set([Weapons, Armor, HealingItems,"A"])
          
//Dictionary with an Int:String key:value
var playerInventory: [Int : String]  =  [1 : "Buster Sword",  43 : "Potion", 22: "StrengthBooster"]

In the preceding code, we used some examples of variables, constants, arrays, sets, and dictionaries. First, we see their Objective-C syntax and then the equivalent declarations using Swift's syntax. From this example, we can see how compact Swift is compared with Objective-C.

主站蜘蛛池模板: 眉山市| 苗栗县| 宁南县| 武山县| 鄂尔多斯市| 东港市| 望奎县| 抚顺县| 白山市| 河曲县| 沙湾县| 宝鸡市| 兰考县| 唐海县| 平远县| 滨州市| 汉沽区| 汝城县| 宾川县| 阿拉善盟| 岐山县| 台南市| 大英县| 深圳市| 墨竹工卡县| 北海市| 射洪县| 新蔡县| 南汇区| 额尔古纳市| 雷州市| 甘孜县| 汾阳市| 武冈市| 克山县| 洛隆县| 湖口县| 大悟县| 宁城县| 马龙县| 莱州市|