summaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
-rw-r--r--c++.html.markdown18
-rw-r--r--dart.html.markdown2
-rw-r--r--elixir.html.markdown2
-rw-r--r--julia.html.markdown3
-rw-r--r--markdown.html.markdown235
-rw-r--r--perl6.html.markdown29
-rw-r--r--python.html.markdown4
-rw-r--r--python3.html.markdown2
-rw-r--r--yaml.html.markdown31
-rw-r--r--zh-cn/swift-cn.html.markdown131
10 files changed, 292 insertions, 165 deletions
diff --git a/c++.html.markdown b/c++.html.markdown
index d03092e5..6b452b1b 100644
--- a/c++.html.markdown
+++ b/c++.html.markdown
@@ -801,6 +801,24 @@ void doSomethingWithAFile(const std::string& filename)
// all automatically destroy their contents when they fall out of scope.
// - Mutexes using lock_guard and unique_lock
+// containers with object keys of non-primitive values (custom classes) require
+// compare function in the object itself or as a function pointer. Primitives
+// have default comparators, but you can override it.
+class Foo {
+public:
+ int j;
+ Foo(int a) : j(a) {}
+};
+struct compareFunction {
+ bool operator()(const Foo& a, const Foo& b) const {
+ return a.j < b.j;
+ }
+};
+//this isn't allowed (although it can vary depending on compiler)
+//std::map<Foo, int> fooMap;
+std::map<Foo, int, compareFunction> fooMap;
+fooMap[Foo(1)] = 1;
+fooMap.find(Foo(1)); //true
/////////////////////
// Fun stuff
diff --git a/dart.html.markdown b/dart.html.markdown
index f7601271..fc7b220e 100644
--- a/dart.html.markdown
+++ b/dart.html.markdown
@@ -498,7 +498,7 @@ main() {
## Further Reading
-Dart has a comprehenshive web-site. It covers API reference, tutorials, articles and more, including a
+Dart has a comprehensive web-site. It covers API reference, tutorials, articles and more, including a
useful Try Dart online.
http://www.dartlang.org/
http://try.dartlang.org/
diff --git a/elixir.html.markdown b/elixir.html.markdown
index eedeb227..720e080c 100644
--- a/elixir.html.markdown
+++ b/elixir.html.markdown
@@ -343,6 +343,7 @@ rescue
RuntimeError -> "rescued a runtime error"
_error -> "this will rescue any error"
end
+#=> "rescued a runtime error"
# All exceptions have a message
try do
@@ -351,6 +352,7 @@ rescue
x in [RuntimeError] ->
x.message
end
+#=> "some error"
## ---------------------------
## -- Concurrency
diff --git a/julia.html.markdown b/julia.html.markdown
index cba7cd45..220b52a4 100644
--- a/julia.html.markdown
+++ b/julia.html.markdown
@@ -2,6 +2,7 @@
language: Julia
contributors:
- ["Leah Hanson", "http://leahhanson.us"]
+ - ["Pranit Bauva", "http://github.com/pranitbauva1997"]
filename: learnjulia.jl
---
@@ -723,7 +724,7 @@ code_native(square_area, (Float64,))
# ret
#
# Note that julia will use floating point instructions if any of the
-# arguements are floats.
+# arguments are floats.
# Let's calculate the area of a circle
circle_area(r) = pi * r * r # circle_area (generic function with 1 method)
circle_area(5) # 78.53981633974483
diff --git a/markdown.html.markdown b/markdown.html.markdown
index b956a5f2..8961c995 100644
--- a/markdown.html.markdown
+++ b/markdown.html.markdown
@@ -2,45 +2,63 @@
language: markdown
contributors:
- ["Dan Turkel", "http://danturkel.com/"]
+ - ["Jacob Ward", "http://github.com/JacobCWard/"]
filename: markdown.md
---
-Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
-
-Give me as much feedback as you want! / Feel free to fork and pull request!
+Markdown was created by John Gruber in 2004. It's meant to be an easy to read and write syntax which converts easily to HTML (and now many other formats as well).
+Markdown also varies in implementation from one parser to a next. This
+guide will attempt to clarify when features are universal or when they are
+specific to a certain parser.
+
+- [HTML Elements](#html-elements)
+- [Headings](#headings)
+- [Simple Text Styles](#simple-text-styles)
+- [Paragraphs](#paragraphs)
+- [Lists](#lists)
+- [Code blocks](#code-blocks)
+- [Horizontal rule](#horizontal-rule)
+- [Links](#links)
+- [Images](#images)
+- [Miscellany](#miscellany)
+
+## HTML Elements
+Markdown is a superset of HTML, so any HTML file is valid Markdown.
```markdown
-<!-- Markdown is a superset of HTML, so any HTML file is valid Markdown. This
-means we can use HTML elements in Markdown, such as the comment element, and
-they won't be affected by a markdown parser. However, if you create an HTML
-element in your markdown file, you cannot use markdown syntax within that
-element's contents. -->
+<!--This means we can use HTML elements in Markdown, such as the comment element,
+and they won't be affected by a markdown parser. However, if you create an HTML element
+in your markdown file, you cannot use markdown syntax within that element's contents.-->
+```
-<!-- Markdown also varies in implementation from one parser to a next. This
-guide will attempt to clarify when features are universal or when they are
-specific to a certain parser. -->
+## Headings
-<!-- Headings -->
-<!-- You can create HTML elements <h1> through <h6> easily by prepending the
-text you want to be in that element by a number of hashes (#). -->
+You can create HTML elements `<h1>` through `<h6>` easily by prepending the
+text you want to be in that element by a number of hashes (#).
+
+```markdown
# This is an <h1>
## This is an <h2>
### This is an <h3>
#### This is an <h4>
##### This is an <h5>
###### This is an <h6>
+```
+Markdown also provides us with two alternative ways of indicating h1 and h2.
-<!-- Markdown also provides us with two alternative ways of indicating h1 and h2. -->
+```markdown
This is an h1
=============
This is an h2
-------------
+```
+## Simple text styles
-<!-- Simple text styles -->
-<!-- Text can be easily styled as italic or bold using markdown. -->
+Text can be easily styled as italic or bold using markdown.
+```markdown
*This text is in italics.*
_And so is this text._
@@ -50,15 +68,20 @@ __And so is this text.__
***This text is in both.***
**_As is this!_**
*__And this!__*
+```
-<!-- In Github Flavored Markdown, which is used to render markdown files on
-Github, we also have strikethrough: -->
+In Github Flavored Markdown, which is used to render markdown files on
+Github, we also have strikethrough:
+```markdown
~~This text is rendered with strikethrough.~~
+```
+## Paragraphs
-<!-- Paragraphs are a one or multiple adjacent lines of text separated by one or
-multiple blank lines. -->
+Paragraphs are a one or multiple adjacent lines of text separated by one or
+multiple blank lines.
+```markdown
This is a paragraph. I'm typing in a paragraph isn't this fun?
Now I'm in paragraph 2.
@@ -66,16 +89,20 @@ I'm still in paragraph 2 too!
I'm in paragraph three!
+```
-<!-- Should you ever want to insert an HTML <br /> tag, you can end a paragraph
-with two or more spaces and then begin a new paragraph. -->
+Should you ever want to insert an HTML <br /> tag, you can end a paragraph
+with two or more spaces and then begin a new paragraph.
+```markdown
I end with two spaces (highlight me to see them).
There's a <br /> above me!
+```
-<!-- Block quotes are easy and done with the > character. -->
+Block quotes are easy and done with the > character.
+```markdown
> This is a block quote. You can either
> manually wrap your lines and put a `>` before every line or you can let your lines get really long and wrap on their own.
> It doesn't make a difference so long as they start with a `>`.
@@ -84,9 +111,12 @@ There's a <br /> above me!
>> of indentation?
> How neat is that?
-<!-- Lists -->
-<!-- Unordered lists can be made using asterisks, pluses, or hyphens. -->
+```
+
+## Lists
+Unordered lists can be made using asterisks, pluses, or hyphens.
+```markdown
* Item
* Item
* Another item
@@ -102,159 +132,182 @@ or
- Item
- Item
- One last item
+```
+Ordered lists are done with a number followed by a period.
-<!-- Ordered lists are done with a number followed by a period. -->
-
+```markdown
1. Item one
2. Item two
3. Item three
+```
-<!-- You don't even have to label the items correctly and markdown will still
-render the numbers in order, but this may not be a good idea. -->
+You don't even have to label the items correctly and markdown will still
+render the numbers in order, but this may not be a good idea.
+```markdown
1. Item one
1. Item two
1. Item three
-<!-- (This renders the same as the above example) -->
-
-<!-- You can also use sublists. -->
+```
+(This renders the same as the above example)
+You can also use sublists
+```markdown
1. Item one
2. Item two
3. Item three
* Sub-item
* Sub-item
4. Item four
+```
-<!-- There are even task lists. This creates HTML checkboxes. -->
+There are even task lists. This creates HTML checkboxes.
+```markdown
Boxes below without the 'x' are unchecked HTML checkboxes.
- [ ] First task to complete.
- [ ] Second task that needs done
This checkbox below will be a checked HTML checkbox.
- [x] This task has been completed
+```
+
+## Code blocks
-<!-- Code blocks -->
-<!-- You can indicate a code block (which uses the <code> element) by indenting
-a line with four spaces or a tab. -->
+You can indicate a code block (which uses the `<code>` element) by indenting
+a line with four spaces or a tab.
+```markdown
This is code
So is this
+```
-<!-- You can also re-tab (or add an additional four spaces) for indentation
-inside your code. -->
+You can also re-tab (or add an additional four spaces) for indentation
+inside your code
+```markdown
my_array.each do |item|
puts item
end
+```
-<!-- Inline code can be created using the backtick character ` -->
+Inline code can be created using the backtick character `
+```markdown
John didn't even know what the `go_to()` function did!
+```
-<!-- In Github Flavored Markdown, you can use a special syntax for code. -->
-
+In Github Flavored Markdown, you can use a special syntax for code
+```markdown
\`\`\`ruby <!-- except remove those backslashes when you do this, just ```ruby ! -->
def foobar
puts "Hello world!"
end
\`\`\` <!-- here too, no backslashes, just ``` -->
+```
-<!-- The above text doesn't require indenting, plus Github will use syntax
-highlighting of the language you specify after the ``` -->
+The above text doesn't require indenting, plus Github will use syntax
+highlighting of the language you specify after the \`\`\`
-<!-- Horizontal rule (<hr />) -->
-<!-- Horizontal rules are easily added with three or more asterisks or hyphens,
-with or without spaces. -->
+## Horizontal rule
+Horizontal rules (`<hr/>`) are easily added with three or more asterisks or hyphens,
+with or without spaces.
+```markdown
***
---
- - -
****************
+```
-<!-- Links -->
-<!-- One of the best things about markdown is how easy it is to make links. Put
-the text to display in hard brackets [] followed by the url in parentheses (). -->
+## Links
-[Click me!](http://test.com/)
-
-<!-- You can also add a link title using quotes inside the parentheses. -->
+One of the best things about markdown is how easy it is to make links. Put
+the text to display in hard brackets [] followed by the url in parentheses ()
+```markdown
+[Click me!](http://test.com/)
+```
+You can also add a link title using quotes inside the parentheses.
+```markdown
[Click me!](http://test.com/ "Link to Test.com")
-
-<!-- Relative paths work too. -->
-
+```
+Relative paths work too.
+```markdown
[Go to music](/music/).
-
-<!-- Markdown also supports reference style links. -->
-
+```
+Markdown also supports reference style links.
+```markdown
[Click this link][link1] for more info about it!
[Also check out this link][foobar] if you want to.
[link1]: http://test.com/ "Cool!"
[foobar]: http://foobar.biz/ "Alright!"
-
-<!-- The title can also be in single quotes or in parentheses, or omitted
+```
+The title can also be in single quotes or in parentheses, or omitted
entirely. The references can be anywhere in your document and the reference IDs
-can be anything so long as they are unique. -->
-
-<!-- There is also "implicit naming" which lets you use the link text as the id. -->
+can be anything so long as they are unique.
+There is also "implicit naming" which lets you use the link text as the id.
+```markdown
[This][] is a link.
[this]: http://thisisalink.com/
+```
+But it's not that commonly used.
-<!-- But it's not that commonly used. -->
-
-<!-- Images -->
-<!-- Images are done the same way as links but with an exclamation point in front! -->
-
+## Images
+Images are done the same way as links but with an exclamation point in front!
+```markdown
![This is the alt-attribute for my image](http://imgur.com/myimage.jpg "An optional title")
-
-<!-- And reference style works as expected. -->
-
+```
+And reference style works as expected.
+```markdown
![This is the alt-attribute.][myimage]
[myimage]: relative/urls/cool/image.jpg "if you need a title, it's here"
+```
-<!-- Miscellany -->
-<!-- Auto-links -->
-
+## Miscellany
+### Auto-links
+```markdown
<http://testwebsite.com/> is equivalent to
[http://testwebsite.com/](http://testwebsite.com/)
+```
-<!-- Auto-links for emails -->
-
+### Auto-links for emails
+```markdown
<foo@bar.com>
+```
-<!-- Escaping characters -->
-
+### Escaping characters
+```markdown
I want to type *this text surrounded by asterisks* but I don't want it to be
in italics, so I do this: \*this text surrounded by asterisks\*.
+```
-<!-- Keyboard keys -->
-<!-- In Github Flavored Markdown, you can use a <kbd> tag to represent keyboard keys. -->
+### Keyboard keys
+In Github Flavored Markdown, you can use a `<kbd>` tag to represent keyboard keys.
+```markdown
Your computer crashed? Try sending a
<kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>Del</kbd>
+```
+### Tables
-<!-- Tables -->
-<!-- Tables are only available in Github Flavored Markdown and are slightly
-cumbersome, but if you really want it: -->
-
+Tables are only available in Github Flavored Markdown and are slightly
+cumbersome, but if you really want it:
+```markdown
| Col1 | Col2 | Col3 |
| :----------- | :------: | ------------: |
| Left-aligned | Centered | Right-aligned |
| blah | blah | blah |
+```
+or, for the same results
-<!-- or, for the same results -->
-
+```markdown
Col 1 | Col2 | Col3
:-- | :-: | --:
Ugh this is so ugly | make it | stop
-
-<!-- The end! -->
-
```
-
+---
For more info, check out John Gruber's official post of syntax [here](http://daringfireball.net/projects/markdown/syntax) and Adam Pritchard's great cheatsheet [here](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet).
diff --git a/perl6.html.markdown b/perl6.html.markdown
index 45b15f05..3eec19f3 100644
--- a/perl6.html.markdown
+++ b/perl6.html.markdown
@@ -1,10 +1,9 @@
---
-name: perl6
category: language
language: perl6
filename: learnperl6.pl
contributors:
- - ["Nami-Doc", "http://github.com/Nami-Doc"]
+ - ["vendethiel", "http://github.com/vendethiel"]
---
Perl 6 is a highly capable, feature-rich programming language made for at
@@ -374,6 +373,8 @@ say @array[^10]; # you can pass arrays as subscripts and it'll return
say join(' ', @array[15..*]); #=> 15 16 17 18 19
# which is equivalent to:
say join(' ', @array[-> $n { 15..$n }]);
+# Note: if you try to do either of those with an infinite loop,
+# you'll trigger an infinite loop (your program won't finish)
# You can use that in most places you'd expect, even assigning to an array
my @numbers = ^20;
@@ -763,8 +764,9 @@ try {
# and `enum`) are actually packages. (Packages are the lowest common denominator)
# Packages are important - especially as Perl is well-known for CPAN,
# the Comprehensive Perl Archive Network.
-# You usually don't use packages directly: you use `class Package::Name::Here;`,
-# or if you only want to export variables/subs, you can use `module`:
+# You're not supposed to use the package keyword, usually:
+# you use `class Package::Name::Here;` to declare a class,
+# or if you only want to export variables/subs, you can use `module`:
module Hello::World { # Bracketed form
# If `Hello` doesn't exist yet, it'll just be a "stub",
# that can be redeclared as something else later.
@@ -774,11 +776,6 @@ unit module Parse::Text; # file-scoped form
grammar Parse::Text::Grammar { # A grammar is a package, which you could `use`
}
-# NOTE for Perl 5 users: even though the `package` keyword exists,
-# the braceless form is invalid (to catch a "perl5ism"). This will error out:
-# package Foo; # because Perl 6 will think the entire file is Perl 5
-# Just use `module` or the brace version of `package`.
-
# You can use a module (bring its declarations into scope) with `use`
use JSON::Tiny; # if you installed Rakudo* or Panda, you'll have this module
say from-json('[1]').perl; #=> [1]
@@ -870,8 +867,16 @@ LEAVE { say "Runs everytime you leave a block, even when an exception
PRE { say "Asserts a precondition at every block entry,
before ENTER (especially useful for loops)" }
+# exemple:
+for 0..2 {
+ PRE { $_ > 1 } # This is going to blow up with "Precondition failed"
+}
+
POST { say "Asserts a postcondition at every block exit,
after LEAVE (especially useful for loops)" }
+for 0..2 {
+ POST { $_ < 2 } # This is going to blow up with "Postcondition failed"
+}
## * Block/exceptions phasers
sub {
@@ -1239,14 +1244,14 @@ so 'foo!' ~~ / <-[ a..z ] + [ f o ]> + /; # True (the + doesn't replace the left
# Group: you can group parts of your regexp with `[]`.
# These groups are *not* captured (like PCRE's `(?:)`).
so 'abc' ~~ / a [ b ] c /; # `True`. The grouping does pretty much nothing
-so 'fooABCABCbar' ~~ / foo [ A B C ] + bar /;
+so 'foo012012bar' ~~ / foo [ '01' <[0..9]> ] + bar /;
# The previous line returns `True`.
-# We match the "ABC" 1 or more time (the `+` was applied to the group).
+# We match the "012" 1 or more time (the `+` was applied to the group).
# But this does not go far enough, because we can't actually get back what
# we matched.
# Capture: We can actually *capture* the results of the regexp, using parentheses.
-so 'fooABCABCbar' ~~ / foo ( A B C ) + bar /; # `True`. (using `so` here, `$/` below)
+so 'fooABCABCbar' ~~ / foo ( 'A' <[A..Z]> 'C' ) + bar /; # `True`. (using `so` here, `$/` below)
# So, starting with the grouping explanations.
# As we said before, our `Match` object is available as `$/`:
diff --git a/python.html.markdown b/python.html.markdown
index 2b43c5fc..f8f712d3 100644
--- a/python.html.markdown
+++ b/python.html.markdown
@@ -458,7 +458,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order.
# You can define functions that take a variable number of
-# positional args, which will be interpreted as a tuple if you do not use the *
+# positional args, which will be interpreted as a tuple by using *
def varargs(*args):
return args
@@ -466,7 +466,7 @@ varargs(1, 2, 3) # => (1, 2, 3)
# You can define functions that take a variable number of
-# keyword args, as well, which will be interpreted as a dict if you do not use **
+# keyword args, as well, which will be interpreted as a dict by using **
def keyword_args(**kwargs):
return kwargs
diff --git a/python3.html.markdown b/python3.html.markdown
index 2398e7ac..1f9d0e42 100644
--- a/python3.html.markdown
+++ b/python3.html.markdown
@@ -689,7 +689,7 @@ i.age # => raises an AttributeError
# You can import modules
import math
-print(math.sqrt(16)) # => 4
+print(math.sqrt(16)) # => 4.0
# You can get specific functions from a module
from math import ceil, floor
diff --git a/yaml.html.markdown b/yaml.html.markdown
index 6e3e2c94..62f08fb9 100644
--- a/yaml.html.markdown
+++ b/yaml.html.markdown
@@ -3,6 +3,7 @@ language: yaml
filename: learnyaml.yaml
contributors:
- ["Adam Brenecki", "https://github.com/adambrenecki"]
+ - ["Suhas SG", "https://github.com/jargnar"]
---
YAML is a data serialisation language designed to be directly writable and
@@ -66,14 +67,19 @@ a_nested_map:
# Maps don't have to have string keys.
0.25: a float key
-# Keys can also be multi-line objects, using ? to indicate the start of a key.
+# Keys can also be complex, like multi-line objects
+# We use ? followed by a space to indicate the start of a complex key.
? |
This is a key
that has multiple lines
: and this is its value
-# YAML also allows collection types in keys, but many programming languages
-# will complain.
+# YAML also allows mapping between sequences with the complex key syntax
+# Some language parsers might complain
+# An example
+? - Manchester United
+ - Real Madrid
+: [ 2001-01-01, 2002-02-02 ]
# Sequences (equivalent to lists or arrays) look like this:
a_sequence:
@@ -101,12 +107,31 @@ json_seq: [3, 2, 1, "takeoff"]
anchored_content: &anchor_name This string will appear as the value of two keys.
other_anchor: *anchor_name
+# Anchors can be used to duplicate/inherit properties
+base: &base
+ name: Everyone has same name
+
+foo: &foo
+ <<: *base
+ age: 10
+
+bar: &bar
+ <<: *base
+ age: 20
+
+# foo and bar would also have name: Everyone has same name
+
# YAML also has tags, which you can use to explicitly declare types.
explicit_string: !!str 0.5
# Some parsers implement language specific tags, like this one for Python's
# complex number type.
python_complex_number: !!python/complex 1+2j
+# We can also use yaml complex keys with language specific tags
+? !!python/tuple [5, 7]
+: Fifty Seven
+# Would be {(5, 7): 'Fifty Seven'} in python
+
####################
# EXTRA YAML TYPES #
####################
diff --git a/zh-cn/swift-cn.html.markdown b/zh-cn/swift-cn.html.markdown
index 28001e3f..3efe4941 100644
--- a/zh-cn/swift-cn.html.markdown
+++ b/zh-cn/swift-cn.html.markdown
@@ -5,7 +5,8 @@ contributors:
- ["Grant Timmerman", "http://github.com/grant"]
translators:
- ["Xavier Yao", "http://github.com/xavieryao"]
- - ["Joey Huang", "http://github.com/kamidox"]
+ - ["Joey Huang", "http://github.com/kamidox"]
+ - ["CY Lim", "http://github.com/cylim"]
lang: zh-cn
---
@@ -13,13 +14,13 @@ Swift 是 Apple 开发的用于 iOS 和 OS X 开发的编程语言。Swift 于20
Swift 的官方语言教程 [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) 可以从 iBooks 免费下载.
-亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/RoadMapiOS/index.html) ——一个完整的Swift 教程
+亦可参阅:Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/DevelopiOSAppsSwift/) ——一个完整的Swift 教程
```swift
// 导入外部模块
import UIKit
-//
+//
// MARK: 基础
//
@@ -28,12 +29,14 @@ import UIKit
// TODO: TODO 标记
// FIXME: FIXME 标记
-println("Hello, world")
+// Swift2.0 println() 及 print() 已经整合成 print()。
+print("Hello, world") // 这是原本的 println(),会自动进入下一行
+print("Hello, world", appendNewLine: false) // 如果不要自动进入下一行,需设定进入下一行为 false
// 变量 (var) 的值设置后可以随意改变
// 常量 (let) 的值设置后不能改变
var myVariable = 42
-let øπΩ = "value" // 可以支持 unicode 变量名
+let øπΩ = "value" // 可以支持 unicode 变量名
let π = 3.1415926
let myConstant = 3.1415926
let explicitDouble: Double = 70 // 明确指定变量类型为 Double ,否则编译器将自动推断变量类型
@@ -46,16 +49,17 @@ let piText = "Pi = \(π), Pi 2 = \(π * 2)" // 格式化字符串
// 条件编译
// 使用 -D 定义编译开关
#if false
- println("Not printed")
+ print("Not printed")
let buildValue = 3
#else
let buildValue = 7
#endif
-println("Build value: \(buildValue)") // Build value: 7
+print("Build value: \(buildValue)") // Build value: 7
/*
- Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None
-
+ Optionals 是 Swift 的新特性,它允许你存储两种状态的值给 Optional 变量:有效值或 None 。
+ 可在值名称后加个问号 (?) 来表示这个值是 Optional。
+
Swift 要求所有的 Optinal 属性都必须有明确的值,如果为空,则必须明确设定为 nil
Optional<T> 是个枚举类型
@@ -67,13 +71,17 @@ var someOptionalString2: Optional<String> = "optional"
if someOptionalString != nil {
// 变量不为空
if someOptionalString!.hasPrefix("opt") {
- println("has the prefix")
+ print("has the prefix")
}
-
+
let empty = someOptionalString?.isEmpty
}
someOptionalString = nil
+/*
+ 使用 (!) 可以解决无法访问optional值的运行错误。若要使用 (!)来强制解析,一定要确保 Optional 里不是 nil参数。
+*/
+
// 显式解包 optional 变量
var unwrappedString: String! = "Value is expected."
// 下面语句和上面完全等价,感叹号 (!) 是个后缀运算符,这也是个语法糖
@@ -94,7 +102,7 @@ anyObjectVar = "Changed value to a string, not good practice, but possible."
/*
这里是注释
-
+
/*
支持嵌套的注释
*/
@@ -116,6 +124,7 @@ shoppingList[1] = "bottle of water"
let emptyArray = [String]() // 使用 let 定义常量,此时 emptyArray 数组不能添加或删除内容
let emptyArray2 = Array<String>() // 与上一语句等价,上一语句更常用
var emptyMutableArray = [String]() // 使用 var 定义变量,可以向 emptyMutableArray 添加数组元素
+var explicitEmptyMutableStringArray: [String] = [] // 与上一语句等价
// 字典
var occupations = [
@@ -126,6 +135,7 @@ occupations["Jayne"] = "Public Relations" // 修改字典,如果 key 不存
let emptyDictionary = [String: Float]() // 使用 let 定义字典常量,字典常量不能修改里面的值
let emptyDictionary2 = Dictionary<String, Float>() // 与上一语句类型等价,上一语句更常用
var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量
+var explicitEmptyMutableDictionary: [String: Float] = [:] // 与上一语句类型等价
//
@@ -136,21 +146,21 @@ var emptyMutableDictionary = [String: Float]() // 使用 var 定义字典变量
let myArray = [1, 1, 2, 3, 5]
for value in myArray {
if value == 1 {
- println("One!")
+ print("One!")
} else {
- println("Not one!")
+ print("Not one!")
}
}
// 字典的 for 循环
var dict = ["one": 1, "two": 2]
for (key, value) in dict {
- println("\(key): \(value)")
+ print("\(key): \(value)")
}
// 区间的 loop 循环:其中 `...` 表示闭环区间,即[-1, 3];`..<` 表示半开闭区间,即[-1,3)
for i in -1...shoppingList.count {
- println(i)
+ print(i)
}
shoppingList[1...2] = ["steak", "peacons"]
// 可以使用 `..<` 来去掉最后一个元素
@@ -163,7 +173,7 @@ while i < 1000 {
// do-while 循环
do {
- println("hello")
+ print("hello")
} while 1 == 2
// Switch 语句
@@ -177,7 +187,7 @@ case "cucumber", "watercress":
let vegetableComment = "That would make a good tea sandwich."
case let localScopeValue where localScopeValue.hasSuffix("pepper"):
let vegetableComment = "Is it a spicy \(localScopeValue)?"
-default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句
+default: // 在 Swift 里,switch 语句的 case 必须处理所有可能的情况,如果 case 无法全部处理,则必须包含 default语句
let vegetableComment = "Everything tastes good in soup."
}
@@ -219,8 +229,8 @@ let pricesTuple = getGasPrices()
let price = pricesTuple.2 // 3.79
// 通过下划线 (_) 来忽略不关心的值
let (_, price1, _) = pricesTuple // price1 == 3.69
-println(price1 == pricesTuple.1) // true
-println("Gas price: \(price)")
+print(price1 == pricesTuple.1) // true
+print("Gas price: \(price)")
// 可变参数
func setup(numbers: Int...) {
@@ -248,7 +258,7 @@ func swapTwoInts(inout a: Int, inout b: Int) {
var someIntA = 7
var someIntB = 3
swapTwoInts(&someIntA, &someIntB)
-println(someIntB) // 7
+print(someIntB) // 7
//
@@ -256,7 +266,7 @@ println(someIntB) // 7
//
var numbers = [1, 2, 6]
-// 函数是闭包的一个特例
+// 函数是闭包的一个特例 ({})
// 闭包实例
// `->` 分隔了闭包的参数和返回值
@@ -296,7 +306,7 @@ print(numbers) // [3, 6, 18]
struct NamesTable {
let names = [String]()
-
+
// 自定义下标运算符
subscript(index: Int) -> String {
return names[index]
@@ -306,7 +316,7 @@ struct NamesTable {
// 结构体有一个自动生成的隐含的命名构造函数
let namesTable = NamesTable(names: ["Me", "Them"])
let name = namesTable[1]
-println("Name is \(name)") // Name is Them
+print("Name is \(name)") // Name is Them
//
// MARK: 类
@@ -329,7 +339,7 @@ public class Shape {
internal class Rect: Shape {
// 值属性 (Stored properties)
var sideLength: Int = 1
-
+
// 计算属性 (Computed properties)
private var perimeter: Int {
get {
@@ -340,11 +350,11 @@ internal class Rect: Shape {
sideLength = newValue / 4
}
}
-
+
// 延时加载的属性,只有这个属性第一次被引用时才进行初始化,而不是定义时就初始化
// subShape 值为 nil ,直到 subShape 第一次被引用时才初始化为一个 Rect 实例
lazy var subShape = Rect(sideLength: 4)
-
+
// 监控属性值的变化。
// 当我们需要在属性值改变时做一些事情,可以使用 `willSet` 和 `didSet` 来设置监控函数
// `willSet`: 值改变之前被调用
@@ -352,14 +362,14 @@ internal class Rect: Shape {
var identifier: String = "defaultID" {
// `willSet` 的参数是即将设置的新值,参数名可以指定,如果没有指定,就是 `newValue`
willSet(someIdentifier) {
- println(someIdentifier)
+ print(someIdentifier)
}
// `didSet` 的参数是已经被覆盖掉的旧的值,参数名也可以指定,如果没有指定,就是 `oldValue`
didSet {
- println(oldValue)
+ print(oldValue)
}
}
-
+
// 命名构造函数 (designated inits),它必须初始化所有的成员变量,
// 然后调用父类的命名构造函数继续初始化父类的所有变量。
init(sideLength: Int) {
@@ -367,13 +377,13 @@ internal class Rect: Shape {
// 必须显式地在构造函数最后调用父类的构造函数 super.init
super.init()
}
-
+
func shrink() {
if sideLength > 0 {
--sideLength
}
}
-
+
// 函数重载使用 override 关键字
override func getArea() -> Int {
return sideLength * sideLength
@@ -394,16 +404,16 @@ class Square: Rect {
}
var mySquare = Square()
-println(mySquare.getArea()) // 25
+print(mySquare.getArea()) // 25
mySquare.shrink()
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// 类型转换
let aShape = mySquare as Shape
// 使用三个等号来比较是不是同一个实例
if mySquare === aShape {
- println("Yep, it's mySquare")
+ print("Yep, it's mySquare")
}
class Circle: Shape {
@@ -411,12 +421,12 @@ class Circle: Shape {
override func getArea() -> Int {
return 3 * radius * radius
}
-
+
// optional 构造函数,可能会返回 nil
init?(radius: Int) {
self.radius = radius
super.init()
-
+
if radius <= 0 {
return nil
}
@@ -425,13 +435,13 @@ class Circle: Shape {
// 根据 Swift 类型推断,myCircle 是 Optional<Circle> 类型的变量
var myCircle = Circle(radius: 1)
-println(myCircle?.getArea()) // Optional(3)
-println(myCircle!.getArea()) // 3
+print(myCircle?.getArea()) // Optional(3)
+print(myCircle!.getArea()) // 3
var myEmptyCircle = Circle(radius: -1)
-println(myEmptyCircle?.getArea()) // "nil"
+print(myEmptyCircle?.getArea()) // "nil"
if let circle = myEmptyCircle {
// 此语句不会输出,因为 myEmptyCircle 变量值为 nil
- println("circle is not nil")
+ print("circle is not nil")
}
@@ -461,7 +471,7 @@ enum BookName: String {
case John = "John"
case Luke = "Luke"
}
-println("Name: \(BookName.John.rawValue)")
+print("Name: \(BookName.John.rawValue)")
// 与特定数据类型关联的枚举
enum Furniture {
@@ -469,7 +479,7 @@ enum Furniture {
case Desk(height: Int)
// 和 String, Int 关联的枚举记录
case Chair(brand: String, height: Int)
-
+
func description() -> String {
switch self {
case .Desk(let height):
@@ -481,9 +491,9 @@ enum Furniture {
}
var desk: Furniture = .Desk(height: 80)
-println(desk.description()) // "Desk with 80 cm"
+print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair(brand: "Foo", height: 40)
-println(chair.description()) // "Chair of Foo with 40 cm"
+print(chair.description()) // "Chair of Foo with 40 cm"
//
@@ -512,7 +522,7 @@ protocol ShapeGenerator {
class MyShape: Rect {
var delegate: TransformShape?
-
+
func grow() {
sideLength += 2
@@ -539,21 +549,21 @@ extension Square: Printable {
}
}
-println("Square: \(mySquare)") // Area: 16 - ID: defaultID
+print("Square: \(mySquare)") // Area: 16 - ID: defaultID
// 也可以给系统内置类型添加功能支持
extension Int {
var customProperty: String {
return "This is \(self)"
}
-
+
func multiplyBy(num: Int) -> Int {
return num * self
}
}
-println(7.customProperty) // "This is 7"
-println(14.multiplyBy(3)) // 42
+print(7.customProperty) // "This is 7"
+print(14.multiplyBy(3)) // 42
// 泛型: 和 Java 及 C# 的泛型类似,使用 `where` 关键字来限制类型。
// 如果只有一个类型限制,可以省略 `where` 关键字
@@ -566,7 +576,7 @@ func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? {
return nil
}
let foundAtIndex = findIndex([1, 2, 3, 4], 3)
-println(foundAtIndex == 2) // true
+print(foundAtIndex == 2) // true
// 自定义运算符:
// 自定义运算符可以以下面的字符打头:
@@ -581,11 +591,24 @@ prefix func !!! (inout shape: Square) -> Square {
}
// 当前值
-println(mySquare.sideLength) // 4
+print(mySquare.sideLength) // 4
// 使用自定义的 !!! 运算符来把矩形边长放大三倍
!!!mySquare
-println(mySquare.sideLength) // 12
+print(mySquare.sideLength) // 12
-```
+// 运算符也可以是泛型
+infix operator <-> {}
+func <-><T: Equatable> (inout a: T, inout b: T) {
+ let c = a
+ a = b
+ b = c
+}
+var foo: Float = 10
+var bar: Float = 20
+
+foo <-> bar
+print("foo is \(foo), bar is \(bar)") // "foo is 20.0, bar is 10.0"
+
+```