2018-04-11 23:00:19 weixin_40840896 阅读数 390
  • Swift 2.1 基础实操高清视频教程

    我们通过一些代码片段学习Swift中的constant和variable、各种基本types和tuple以及Swift中重要的语言特性之一: type inference。并录制了泊学高清视频,同步搭配了泊阅文档,为开发者朋友们的学习提供了一种全新的学习视觉享受。

    8448 人正在学习 去看看 崔轶

该文章翻译自apple官方文档:The Swift Programming Language(Swift 4.1)

Swift 4.0 版本相对于前面几个版本来说,已经比较稳定,也终于可以利用下班时间关注和学习它了,鉴于官方文档是英文的,自己翻译过后也需要记录下来,那就一起分享吧,一定有理解不充分和不足的部分,请斧正!

既然不知从哪里开始合适,那就一页页来吧~

About Swift

Swift is a fantastic way to write software, whether it’s for phones, desktops, servers, or anything else that runs code. It’s a safe, fast, and interactive programming language that combines the best in modern language thinking with wisdom from the wider Apple engineering culture and the diverse contributions from its open-source community. The compiler is optimized for performance and the language is optimized for development, without compromising on either.

Swift is friendly to new programmers. It’s an industrial-quality programming language that’s as expressive and enjoyable as a scripting language. Writing Swift code in a playground lets you experiment with code and see the results immediately, without the overhead of building and running an app.

Swift defines away large classes of common programming errors by adopting modern programming patterns:

  • Variables are always initialized before use.

  • Array indices are checked for out-of-bounds errors.

  • Integers are checked for overflow.

  • Optionals ensure that nil values are handled explicitly.

  • Memory is managed automatically.

  • Error handling allows controlled recovery from unexpected failures.

Swift code is compiled and optimized to get the most out of modern hardware. The syntax and standard library have been designed based on the guiding principle that the obvious way to write your code should also perform the best. Its combination of safety and speed make Swift an excellent choice for everything from “Hello, world!” to an entire operating system.

Swift combines powerful type inference and pattern matching with a modern, lightweight syntax, allowing complex ideas to be expressed in a clear and concise manner. As a result, code is not just easier to write, but easier to read and maintain as well.

Swift has been years in the making, and it continues to evolve with new features and capabilities. Our goals for Swift are ambitious. We can’t wait to see what you create with it.


Swift 是一门写软件很好用的语言,不管是对于手机端,前端,后台还是任何一个可以运行代码的平台,它都是一门安全,快速,能相互影响的编程语言,它结合了最好的现代化语言思维和来自更广的苹果工程文化的智慧以及来自开源社区的多种多样的贡献。这编译器在性能方面做了优化,并且这语言在开发上做了优化,不妥协。

Swift 对于初学者是很友好的,是一门既满足工业标准又脚本语言一样充满表现力趣味编程语言

Swift通过接受现代化编程模式定义了大量的常用的编程错误的类

         变量在用之前要被初始化

         检查数组时候越界

         检查整数是否溢出

         确保nil 明确地被处理过

         自动管理内存

         错误处理允许从异常失败中控制恢复。

Swift 代码充分利用现代硬件编译和优化。它的语法和标准库是基于‘写代码很显然的方式也应该运行的最好’的指导原则设计的。

安全和快速的结合使得Swift 无论从最简单的‘hello world’还是对于开发整个操作系统,都成为一个杰出的选择

Swift 结合了强大的类型推断和模式匹配与现代的,轻量级的语法,使复杂的想法,以明确和简明的方式表达。因此,代码不仅容易编写,而且更易于阅读和维护。

Swift 已经发展多年,并且在继续发展新的特点和功能。我们的目标远大,我们已经迫不及待地想看看你能用它创造出什么了。




2017-06-30 10:04:16 aa654403231 阅读数 1852
  • Swift 2.1 基础实操高清视频教程

    我们通过一些代码片段学习Swift中的constant和variable、各种基本types和tuple以及Swift中重要的语言特性之一: type inference。并录制了泊学高清视频,同步搭配了泊阅文档,为开发者朋友们的学习提供了一种全新的学习视觉享受。

    8448 人正在学习 去看看 崔轶

重点是app 内部切换

1.配置languege.strings.infoPist.Strings












2.LocalizationTool.swift,实现内部切换

//
//  LocalizationTool.swift
//  IFXY
//
//  Created by LiuXing on 2017/3/7.
//  Copyright © 2017年 IFly. All rights reserved.
//

import UIKit

class LocalizationTool: NSObject {
     static let shareInstance = LocalizationTool()

     let def = UserDefaults.standard
     var bundle : Bundle?
     
     func valueWithKey(key: String!) -> String {
          let bundle = LocalizationTool.shareInstance.bundle
          let str = bundle?.localizedString(forKey: key, value: nil, table: "Language")
          return str!
     }
//    class func valueWithKey(key: String!) -> String {
//        
//        let languageString = SynthesizerSettingTool.shareIntance.vocieParams?.languageType
//        let path = Bundle.main.path(forResource: languageString!, ofType: "lproj")
//        let value = (Bundle.init(path: path!)?.localizedString(forKey: key, value: nil, table: "Language"))!
//        return value
//    }
     
     func setLanguage(langeuage:String) {
          var str=langeuage
          if langeuage=="" || langeuage==nil{
               
               let languages:[String]=UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
               let str2:String=languages[0]
               if ((str2=="zh-Hans-CN")||(str2=="zh-Hans")){
                    str="zh-Hans"
               }else{
                    str="en"
               }
               
          }
          UserDefaults.standard.set(str, forKey: "langeuage")
          UserDefaults.standard.synchronize()
          let path = Bundle.main.path(forResource:str , ofType: "lproj")
          bundle = Bundle(path: path!)
//          def.set(langeuage, forKey: UserLanguage)
//          def.synchronize()
          NotificationCenter.default.post(name: NSNotification.Name(rawValue: "LanguageChanged"), object: nil)

          
     }
}

3.在appdelegate里面     

       var languege:String=""
//        guard languege==UserDefaults.standard.value(forKey: "langeuage") as! String else{
//               languege=""
//        }
        if  (UserDefaults.standard.value(forKey: "langeuage")) != nil {
            languege=UserDefaults.standard.value(forKey: "langeuage") as! String
        }
        LocalizationTool.shareInstance.setLanguage(langeuage: languege)

4.语言切换界面



  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: false)
        selectCol = indexPath.row
        tableView.reloadData()
        if   indexPath.row == 0 { 
 
          LocalizationTool.shareInstance.setLanguage(langeuage: "zh-Hans")
        }  else { 
 
          LocalizationTool.shareInstance.setLanguage(langeuage: "en")
        }
     

    
    }
点击切换语言之后,需要立即修改之前缓存的页面

 

        NotificationCenter.default.addObserver(self, selector: #selector(changeLanguage), name: NSNotification.Name(rawValue: "LanguageChanged"), object: nil)

页面所有的viewdidload方法里面加上监听

 

 func changeLanguage(){
           items = [["title": LocalizationTool.shareInstance.valueWithKey(key: "my_language_zh")],["title": LocalizationTool.shareInstance.valueWithKey(key: "trans_title_en")]]
          self.title = LocalizationTool.shareInstance.valueWithKey(key: "my_language_switch")//"切换语言"
          
          if (UserDefaults.standard.value(forKey: "langeuage") as! String) == "en"{ // 英语
               selectCol = 1
          } else {
               selectCol = 0
          }
          m_TableView.reloadData()
    }

tip:日期选择器

fileprivate lazy var datePicker:UIDatePicker = {[unowned self] in
        let datePic = UIDatePicker()
        datePic.backgroundColor = UIColor.white
     let languege=UserDefaults.standard.value(forKey: "langeuage") as! String
     var sexstr=UserAccountTool.shareIntance.account?.sex
     if languege=="en" {
          datePic.locale = Locale(identifier: "en")

 }else{
        datePic.locale = Locale(identifier: "zh_CN")  
     }
//        datePic.locale = Locale(identifier: "zh_CN")
        return datePic
        
    }()


2018-04-13 00:10:25 weixin_40840896 阅读数 2807
  • Swift 2.1 基础实操高清视频教程

    我们通过一些代码片段学习Swift中的constant和variable、各种基本types和tuple以及Swift中重要的语言特性之一: type inference。并录制了泊学高清视频,同步搭配了泊阅文档,为开发者朋友们的学习提供了一种全新的学习视觉享受。

    8448 人正在学习 去看看 崔轶

该文章翻译自apple官方文档:The Swift Programming Language(Swift 4.1)

A Swift Tour  -- 一个Swift 旅行

Tradition suggests that the first program in a new language should print the words “Hello, world!” on the screen. In Swift, this can be done in a single line:
print("Hello, world!")

译:传统认为,一种新语言的第一个程序应该打印“Hello world!”在屏幕上。 用Swift,它可以用简单的一行代码搞定。

If you have written code in C or Objective-C, this syntax looks familiar to you—in Swift, this line of code is a complete program. You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a main()function. You also don’t need to write semicolons at the end of every statement.

译:如果你用C或 OC写代码,这语法看起来很熟悉 —— 在 Swift里,这行代码就是一个完整的程序。你不需要为输入/输出或字符串处理之类的功能导入单独的库。在全局范围内编写的代码用作程序的入口点,所以你不需要一个主函数功能。你也不需要在每一个语句的末尾写分号。

This tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks. Don’t worry if you don’t understand something—everything introduced in this tour is explained in detail in the rest of this book.

译:这个旅行给你足够的信息可以开始用Swift写代码,它展示给你怎样完成各项编程任务。不要担心如果你不理解一些部分 ——这个旅行里每一项在本书的其他部分都有详细的介绍。

NOTE

For the best experience, open this chapter as a playground in Xcode. Playgrounds allow you to edit the code listings and see the result immediately.

Download Playground

提示:

为了一个更好的体验,在Xcode的里用一个playground打开本章内容,Playgrounds 允许你编辑代码列表并且立马看结果。

 

 

Simple Values -- 简单的值

Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.

  1. var myVariable = 42
  2. myVariable = 50
  3. let myConstant = 42

译:用 let 表示常量,用 var 表示变量,这个常量的值在编译时不需要知道,但是你必须马上赋给它一个确切的值。这意味着你可以用常量去为一个你定义的值命名,这个值可以在多处使用。

A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that myVariable is an integer because its initial value is an integer.
If the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.

  1. let implicitInteger = 70
  2. let implicitDouble = 70.0
  3. let explicitDouble: Double = 70

EXPERIMENT

Create a constant with an explicit type of Float and a value of 4.
 

译:常量或变量必须与你赋给它的值有同样的类型.然而,然而你并不必须写出具体的类型.当你创建一个常量或变量时提供一个值可以让编译器判断它的类型,在上面的例子中,编译器判断 myVarible 是一个整数因为它的初始化值是一个整数.

如果这个初始化的值没有提供足够的信息(或者如果没有初始化的值),可以通过在变量后面写下指定的类型,用冒号隔开

 尝试1
创建一个有明确类型为Float的常量,值为4

 

Values are never implicitly converted to another type. If you need to convert a value to a different type, explicitly make an instance of the desired type.

  1. let label = "The width is "
  2. let width = 94
  3. let widthLabel = label + String(width)

EXPERIMENT

Try removing the conversion to String from the last line. What error do you get?

译:这个值是绝不能换成其他类型的,如果你需要将值转换为不同的类型,明确地做一个期望类型的实例
实验
试着从最后一行移除String转换,你得到什么错误?

 

There’s an even simpler way to include values in strings: Write the value in parentheses, and write a backslash (\) before the parentheses. For example:

  1. let apples = 3
  2. let oranges = 5
  3. let appleSummary = "I have \(apples) apples."
  4. let fruitSummary = "I have \(apples + oranges) pieces of fruit."

EXPERIMENT

Use \() to include a floating-point calculation in a string and to include someone’s name in a greeting.
 

译:这里有一个更简单的方式去在字符串里包含值:将这个值写进圆括号()里,并且在原括号前写一个反斜杠(\),例如:code
实验
用\()去在字符串里包含一个浮点值的计算并且在问候语里包含某个人的名字

 

Use three double quotation marks (""") for strings that take up multiple lines. Indentation at the start of each quoted line is removed, as long as it matches the indentation of the closing quotation marks. For example:

  1. let quotation = """
    I said "I have \(apples) apples."
    And then I said "I have \(apples + oranges) pieces of fruit."
    """

译:用三个双引号(" " ")来表示多行字符串。只要它匹配上结束引用标记的缩格,在每个引用行行头的缩格就是被删除的,例如:code

Create arrays and dictionaries using brackets ([]), and access their elements by writing the index or key in brackets. A comma is allowed after the last element.

  1. var shoppingList = ["catfish", "water", "tulips", "blue paint"]
    shoppingList[1] = "bottle of water"
    
    var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
    ]
    occupations["Jayne"] = "Public Relations"

To create an empty array or dictionary, use the initializer syntax.

  1. let emptyArray = [String]()
    let emptyDictionary = [String: Float]()

If type information can be inferred, you can write an empty array as [] and an empty dictionary as [:]—for example, when you set a new value for a variable or pass an argument to a function.

  1. shoppingList = []
  2. occupations = [:]

译:
1.用([]) 方括号创建数组和字典,通过元素的索引或字典的key值访问到方括号中的元素。最后一个元素后面允许逗号.ex: code

2. 用初始化语法创建一个空数组或字典

3.如果类型信息可以被判断,你可以写一个空数组[],或空字典[:] -- 例如,当你设置一个值为一个变量或传一个参数给函数时.

 

 

2018-06-03 22:38:07 qq_35568359 阅读数 247
  • Swift 2.1 基础实操高清视频教程

    我们通过一些代码片段学习Swift中的constant和variable、各种基本types和tuple以及Swift中重要的语言特性之一: type inference。并录制了泊学高清视频,同步搭配了泊阅文档,为开发者朋友们的学习提供了一种全新的学习视觉享受。

    8448 人正在学习 去看看 崔轶

自己算是半个果粉吧,几年前看到Apple发布最新编程语言,作为科班出身,毕业之后几乎没碰到代码,甚是惭愧。

在Swift发布到第四版的时候,我开始正儿八经学习之了,原因大家可能也清楚,语言发展初期改动较大。

语言的基础学习:http://www.swift51.com/swift4.0/ 中文版本

iOS学习资源:2本经典入门书,国内有针对性的翻译版:精通iOS开发第8版,英文最新版,作者准备不再更新,估计直接跳到第十版吧。

2017-04-18 10:33:16 csdn_lisword 阅读数 289
  • Swift 2.1 基础实操高清视频教程

    我们通过一些代码片段学习Swift中的constant和variable、各种基本types和tuple以及Swift中重要的语言特性之一: type inference。并录制了泊学高清视频,同步搭配了泊阅文档,为开发者朋友们的学习提供了一种全新的学习视觉享受。

    8448 人正在学习 去看看 崔轶

Swift 3.0 学习笔记-4-控制流

标签(空格分隔): iOS Swift


前言:
swift3.0 学习笔记主要参考苹果开发者官网The Swift Programming Language (Swift 3.1)教程 以及 Swift 中文网
更纯粹的阅读的体验请移步至:
https://www.zybuluo.com/kakadee/note/726184



1. For-In Loops

使用for-in来遍历集合中的项目,比如数组的范围,排列中的项或者字符串中的字符。Swift 3.0 中已经移除了For-Condition-Increment的形式。
下面的例子打印了表中的5个元素

for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5 
// 2 times 5 is 10 
// 3 times 5 is 15 
// 4 times 5 is 20 
// 5 times 5 is 25 

如果不需要范围的值,可以用下划线替代变量名来忽略这些值:

let base = 3
let power = 10
var answer = 1
for _ in 1...power {
    answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// prints "3 to the power of 10 is 59049" 

规定步长使用from:to:by:(不包含终点)

let minutes = 60
let minuteInterval = 5
for tickMark in stride(from: 0, to: minutes, by: minuteInterval) {
    // render the tick mark every 5 minutes (0, 5, 10, 15 ... 45, 50, 55)
}

另一种方式,使用from:through:by: (包含终点)

let hours = 12
let hourInterval = 3
for tickMark in stride(from: 3, through: hours, by: hourInterval) {
    // render the tick mark every 3 hours (3, 6, 9, 12)
}

2. While Loops

while Loops的两种形式。

while condition {
    statements
}
repeat {
    statements
} while condition

3. Conditional Statements - 条件语句

If

没什么好说的。大家都会用

switch

switch some value to consider {
case value 1:
    respond to value 1
case value 2,
     value 3:
    respond to value 2 or 3
default:
    otherwise, do something else
}

注意:swift 3.0 中的switch语句和C中的不一样。break不是必须的,当然加上亦可。另一个区别就是当前一条case判断是空的话不会自动跳到下一条case判断语句

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a": // Invalid, the case has an empty body
case "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// This will report a compile-time error.
// 这种情况下会报错

如果想让switch的一条判定同时满足多种情况,可以放在一起写,用逗号分隔即可。

let anotherCharacter: Character = "a"
switch anotherCharacter {
case "a", "A":
    print("The letter A")
default:
    print("Not the letter A")
}
// Prints "The letter A"

范围匹配
switch中case的值可以检查他们内在的范围。这个例子使用数字范围可以提供任意大小数字的自然语言计数。

et approximateCount = 62
let countedThings = "moons orbiting Saturn"
let naturalCount: String
switch approximateCount {
case 0:
    naturalCount = "no"
case 1..<5:
    naturalCount = "a few"
case 5..<12:
    naturalCount = "several"
case 12..<100:
    naturalCount = "dozens of"
case 100..<1000:
    naturalCount = "hundreds of"
default:
    naturalCount = "many"
}
print("There are \(naturalCount) \(countedThings).")
// Prints "There are dozens of moons orbiting Saturn."

元组
可以使用元组在相同的switch语句中测试多个值。每一个元组中的元素都可以试着和范围中不同的值进行匹配。另外,用下划线(_)标示符来匹配任意可能的值。

下面例子中使用一个点坐标(x,y),用元组型(Int, Int)来表示,可以在下面的图中分类出来:

let somePoint = (1, 1)
switch somePoint {
case (0, 0):
    print("\(somePoint) is at the origin")
case (_, 0):
    print("\(somePoint) is on the x-axis")
case (0, _):
    print("\(somePoint) is on the y-axis")
case (-2...2, -2...2):
    print("\(somePoint) is inside the box")
default:
    print("\(somePoint) is outside of the box")
}
// Prints "(1, 1) is inside the box"

image_1bdvd5hcp11h41a1brue1kpl18vm9.png-17.9kB
Value Bindings 值绑定
一个switch的case能绑定用于匹配临时常量或变量值,在case的分支代码里使用。这就是value binding(值绑定),因为这些值在case的代码体中是临时常量或变量的“边界”。

下面的例子有一个点(x,y),用元组型(Int,Int)来表示,在图种展示出来如下:

let anotherPoint = (2, 0)
switch anotherPoint {
case (let x, 0):
    print("on the x-axis with an x value of \(x)")
case (0, let y):
    print("on the y-axis with a y value of \(y)")
case let (x, y):
    print("somewhere else at (\(x), \(y))")
}
// Prints "on the x-axis with an x value of 2"

Where

switch的case能使用where子句来进一步判断条件。 下面的例子将点(x,y)在下图种分类:

let yetAnotherPoint = (1, -1)
switch yetAnotherPoint {
case let (x, y) where x == y:
    print("(\(x), \(y)) is on the line x == y")
case let (x, y) where x == -y:
    print("(\(x), \(y)) is on the line x == -y")
case let (x, y):
    print("(\(x), \(y)) is just some arbitrary point")
}
// Prints "(1, -1) is on the line x == -y"

image_1bdvdclpm1oie1ndj1ecp69avorm.png-26.6kB
switch语句判断了点是否在绿色斜线上且x == y,或在紫色斜线上且x == -y,或都不是。

4. Control Transfer Statements - 控制转移语句

控制转移语句能改变已经执行代码的顺序,能使代码跳转到别的部分。Swift有四个句子:

  • continue
  • break
  • fallthrough
  • return

Continue
Continue语句告诉循环体终止现在的操作,然后开始迭代下一个循环。好像在说“我这次迭代做完啦”,总之不会离开循环体。

Break
Break语句能立即终止整个控制流。可以根据你想要的在switch或循环语句里的任何地方终止整个执行。

Fallthrough
Swift中的Switch不会掉下到case的下方并进入下一个case。因此,整个switch语句会在第一个匹配的case完成后结束。相反,C语言要求你在每个case的末尾插入一个break来防止掉入。相比于C语言,Swift的switch禁止默认掉入让更加简洁和可控,这样避免了执行多个case的错误。
如果你确实需要C式的掉入特性,你可以使用fallthrough关键词。

let integerToDescribe = 5
var description = "The number \(integerToDescribe) is"
switch integerToDescribe {
    case 2, 3, 5, 7, 11, 13, 17, 19:
        description += " a prime number, and also" fallthrough
    default:
        description += " an integer."
}
println(description)
// prints "The number 5 is a prime number, and also an integer." 

Labeled Statements - 标签语句
你可以嵌套循环或在switch语句中嵌套其他的循环,Swift语句种的switch可以创建复杂的控制流结构。 然而,循环和switch语句都可以过早地使用break。因此,有时明确的使用break来终止代码很有用。类似的,如果你有多个嵌套的循环,continue会更有用。

为了做到这一点,你可以用statement label来标记循环或switch,与break或continue语句一起使用这个标签来终止或继续标记语句的执行。

label name: while condition {
    statements
}

这样,你就可以用这个标签来代替这个循环语句。

var count = 0;
countLoop : while count < 5 {
    count += 1;
    if (count == 3) {
        break countLoop
    }
}
print(count)
// 3

Swift编程语言

阅读数 99

swift初见

阅读数 389

没有更多推荐了,返回首页