Swift4 노트-Tour
let explicitDouble: Double = 70
let label = "The width is"
let width = 94
let widthLabel = label + String(width)
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
Control Flow
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
greeting = "Hello,\(name)"
}
else {
print(greeting)
}
let nickName: String? = nil
let fullName: String? = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup")
}
let interestingNumbers = [
"Prime" : [2, 3, 5, 7, 11, 13,],
"Fibonacci" : [1, 1, 2, 3, 5, 8],
"Square" : [1, 4, 9, 16, 25]
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
print(largest)
var n = 2
while n < 2 {
n *= 2
}
print(n)
var m = 2
repeat {
m *= 2
}while m < 2
print(m)
for i in 0..<4 {
print(i)
}
for i in 0...4 {
print(i)
}
Functions and Closures
func greet(person: String, day: String) -> String {
return "Hello \(person), today is \(day)"
}
greet(person: "Bob", day: "Tuesday")
func greet2(_ person: String, on day: String) -> String {
return "Hi \(person), today is \(day)"
}
greet2("John", on: "Wednesday")
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
}
else if score < min {
min = score
}
sum += score
}
return (min,max,sum)
}
let statistics = calculateStatistics(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
func returnFifteen() -> Int {
var y = 10
func add() {
y += 5
}
add()
return y
}
returnFifteen()
func makeIncrementer() -> ((Int) -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne(number:)
}
var increment = makeIncrementer()
increment(7)
// ,
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
for item in list {
if condition(item) {
return true
}
}
return false
}
func lessThanTen(number: Int) -> Bool {
return number < 10
}
var numbers = [20, 19, 7, 12]
// 10
hasAnyMatches(list: numbers, condition: lessThanTen(number:))
let myNumbers = numbers.map({ (number: Int) -> Int in
let result = 3 * number
return result
})
print(myNumbers)
let mappedNumbers = numbers.map({ number in 3 * number})
print(mappedNumbers)
let mappedNumbers2 = numbers.map({ 3 * $0})
print(mappedNumbers2)
//
let sortedNumbers = numbers.sorted {$0 > $1}
print(sortedNumbers)
Objects and Classes
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides"
}
}
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
var namedShape = NamedShape(name: "tom")
namedShape.simpleDescription()
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name:String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return "A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test quare")
test.area()
test.simpleDescription()
class EqualateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)"
}
}
var triangle = EqualateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)
새 값에 직접 이름을 붙일 수도 있습니다
class EqualateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set(myValue) {
sideLength = myValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triangle with sides of length \(sideLength)"
}
}
class TriangleAndSquare {
var triangle: EqualateralTriangle {
willSet {
square.sideLength = newValue.sideLength
}
}
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EqualateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength
Enumerations and Structures
enum Rank: Int {
case ace = 3
case two, three, four, five, six, seven, eight, nine, ten
case jack, queen, king
func simpleDescription() -> String {
switch self {
case .ace:
return "ace"
case .jack:
return "jack"
case .queen:
return "queen"
case .king:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.five
let aceRawValue = ace.rawValue
print(ace.simpleDescription())
enum rank {
case one
case two
}
let one = rank.one
//
//let oneValue = one.rawValue
if let convertedRank = Rank(rawValue: 4) {
let threeDescription = convertedRank.simpleDescription()
}
if let convertedRank2 = Rank(rawValue: 15) {
let threeDescription = convertedRank2.simpleDescription()
}
else {
print("nil")
}
enum Suit {
//
case spades, hearts, diamonds, clubs
func simpleDescription() -> String {
switch self {
case .spades:
return "spades"
case .hearts:
return "hearts"
case .diamonds:
return "diamonds"
case .clubs:
return "clubs"
}
}
func color() -> String {
switch self {
case .spades, .clubs:
return "blackColor"
case .hearts, .diamonds:
return "redColor"
}
}
}
let hearts = Suit.hearts
let heartDescription = hearts.simpleDescription()
let heartsColor = hearts.color()
enum ServerResponse {
case result(String, String)
case failure(String)
case disconnect(String)
}
let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")
let network = ServerResponse.disconnect("404")
switch network {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
print("Failure... \(message)")
case let .disconnect(cause):
print("Network failure \(cause)")
}
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
Protocols and Extensions
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
//
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += "Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
//
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple struture"
mutating func adjust() {
simpleDescription += "(adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
//
enum SimpleEnum: ExampleProtocol {
mutating func adjust() {
switch self {
case let .Result(text):
self = .Result(text + "(first case adjusted)")
case let .Failure(text):
self = .Failure(text + "(second case adjusted)")
}
}
case Result(String)
case Failure(String)
var simpleDescription: String {
get {
switch self {
case .Result("123"):
return "13"
case .Failure(" "):
return " "
default:
return "get error"
}
}
set {
switch self {
case .Result("123"):
self = .Result("12")
case .Failure(" "):
self = .Failure("312")
default:
self = .Failure("3333")
}
}
}
}
var enumConformToProtocolTest = SimpleEnum.Failure(" ")
enumConformToProtocolTest.adjust()
print("\(enumConformToProtocolTest)")
enumConformToProtocolTest.simpleDescription
enumConformToProtocolTest.simpleDescription = "test"
enumConformToProtocolTest = SimpleEnum.Result("ThirdVal")
enumConformToProtocolTest.simpleDescription
enumConformToProtocolTest.adjust()
enumConformToProtocolTest.simpleDescription
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
var textExtension = 7
textExtension.simpleDescription
textExtension.adjust()
textExtension.simpleDescription
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
//print(protocolValue.anotherProperty)
Error Handling
enum PrinterError: Error {
case outOfPaper
case noToner
case onFire
}
func mySend(job: Int, toPrinter printerName: String) throws -> String {
if printerName == "Never Has Toner" {
throw PrinterError.noToner
}
else if printerName == "Gutenberg" {
throw PrinterError.outOfPaper
}
else if printerName == "Dongdong" {
throw PrinterError.onFire
}
return "Job sent"
}
do {
try mySend(job: 5, toPrinter: "Never Has Toner")
} catch {
print(error)
}
do {
try mySend(job: 5, toPrinter: "Bi sheng")
} catch {
print(error)
}
do {
try mySend(job: 15, toPrinter: "Gutenberg")
} catch PrinterError.outOfPaper {
print("I'll just put this over here, with the rest of the fire.")
} catch let printerError as PrinterError {
print("Printer error: \(printerError).")
} catch {
print(error)
}
let printerSuccess = try? mySend(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? mySend(job: 1885, toPrinter: "Never Has Toner")
func lookforSomething(name: String) throws {
print("1-1")
if name == "" {
print("2-1")
defer {
print("2-2")
}
print("2-3")
}
print("1-2")
defer {
print("1-3")
}
print("1-4")
if name == "hello" {
print("3-1")
defer {
print("3-2")
}
print("3-3")
defer {
print("3-4")
}
}
defer {
print("5-1")
}
}
print("--------")
try? lookforSomething(name: "")
print("--------")
try? lookforSomething(name: "hello")
Generics
func makeArray- (repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..
enum OptionalValue {
case none
case some(Wrapped)
}
var possibleInteger: OptionalValue = .none
possibleInteger = .some(100)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.