0%

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// 计算逆波兰表达式
class Solution {
func evalRPN(_ tokens: [String]) -> Int {

var stack: [Int] = []
for token in tokens {
if isOperator(token: token) {
let right = stack.popLast()!
let left = stack.popLast()!
let result = calculate(right: right, left: left, token: token)
stack.append(result)
} else {
stack.append(Int(token)!)
}
}
return stack.first!
}

func calculate(right: Int, left: Int, token: String) -> Int {
if token == "+" {
return left + right
} else if token == "-" {
return left - right
} else if token == "*" {
return left * right
} else if token == "/" {
return left / right
}
return 0
}

func isOperator(token: String) -> Bool {
return token == "+" || token == "-" || token == "*" || token == "/"
}
}

let solution = Solution()
let array = ["-78","-33","196","+","-19","-","115","+","-","-99","/","-18","8","*","-86","-","-","16","/","26","-14","-","-","47","-","101","-","163","*","143","-","0","-","171","+","120","*","-60","+","156","/","173","/","-24","11","+","21","/","*","44","*","180","70","-40","-","*","86","132","-84","+","*","-","38","/","/","21","28","/","+","83","/","-31","156","-","+","28","/","95","-","120","+","8","*","90","-","-94","*","-73","/","-62","/","93","*","196","-","-59","+","187","-","143","/","-79","-89","+","-"]
let result = solution.evalRPN(array)
print(result)

–EOF–

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import Foundation

/// 前缀类型
//前缀类型
struct Swifter<Base> {
let base: Base
init(_ base: Base) {
self.base = base
}
}
//利用协议扩展属性
protocol SwifterProtocol {}

extension SwifterProtocol {
var swifter: Swifter<Self> {
set { }
get {
return Swifter(self)
}
}
static var swifter: Swifter<Self>.Type {
set { }
get { Swifter<Self>.self }
}
}

//给字符串扩展功能
extension String: SwifterProtocol {}
extension NSString: SwifterProtocol {}
//extension NSMutableString: SwifterProtocol {}
//给Person扩展功能
class Person{}
extension Person: SwifterProtocol {}

// 扩展功能
extension Swifter where Base: ExpressibleByStringLiteral {
var numberCount: Int {
var count = 0
for c in (base as! String) where ("0"..."9").contains(c) {
count += 1
}
return count
}

static func test() {
print("test")
}

mutating func run() {
// self.base = "run"
}
}

extension Swifter where Base: Person {
func run() {
print("跑")
}
}

print("123ooo123".swifter.numberCount)
Person().swifter.run()

String.swifter.test()

var abc = "123"
var def: NSMutableString = "456"
abc.swifter.run()
print(abc)
def.swifter.run()

/////////////////////////

protocol ArrayType {

}
extension Array: ArrayType{}
extension NSArray: ArrayType{}
extension String: ArrayType{}
func isArrayType(_ type: Any.Type) -> Bool {
type is ArrayType.Type
}

print(isArrayType([Int].self))
print(isArrayType([Any].self))
print(isArrayType(NSArray.self))
print(isArrayType(NSMutableArray.self))
print(isArrayType(String.self))

–EOF–

Package.swift

// swift-tools-version:5.1
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
    name: "HelloWorld",
    dependencies: [
        // Dependencies declare other packages that this package depends on.
         .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0-alpha.2"),
    ],
    targets: [
        // Targets are the basic building blocks of a package. A target can define a module or a test suite.
        // Targets can depend on other targets in this package, and on products in packages which this package depends on.
        .target(
            name: "HelloWorld",
            dependencies: ["Vapor"]),
        .testTarget(
            name: "HelloWorldTests",
            dependencies: ["HelloWorld"]),
    ]
)

main.swift

import Vapor
let app = Application(environment: try .detect()) { (service) in
    service.extend(Routes.self) { (routes, container) in
        routes.get("hello") { (req) -> String in
            "Hello World!"
        }
    }
}
try app.run()

–EOF–

方式一

protocol Runnable1: class { }
extension Runnable1 {
    func run() {
    }
}

方式二

@objc protocol Runnable2 {
    @objc optional func run()
    func stop()
}

–EOF–

class Person { }
extension Person {
    private static var age_key = false //占一个字节,省空间
    private static var weight_key = false //占一个字节,省空间
// private static var age_key1: Void? //这种方式也是可以的
// private static var weight_key1: Void?
    var age: Int {
        get {
            objc_getAssociatedObject(self, &Self.age_key) as! Int
        }
        set {
// self abc 都相当于是key
            objc_setAssociatedObject(self, &Self.age_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
        }
    }
    var weight: Int {
        get {
            objc_getAssociatedObject(self, &Self.weight_key) as! Int
        }
        set {
// self abc 都相当于是key
            objc_setAssociatedObject(self, &Self.weight_key, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_ASSIGN)
        }
    }
}
var p = Person()
p.age = 10
print(p.age)
p.weight = 50
print(p.weight)

–EOF–

Test.h

#ifndef Test_h
#define Test_h
#include <stdio.h>
int sum(int v1, int v2);
#endif /* Test_h */

Test.c

#include "Test.h"
int sum(int v1, int v2) {
    return v1 + v2;
}

main.swift

// 重命名c函数
@_silgen_name("sum")
func swift_sum(_ v1: Int32, _ v2: Int32) -> Int32
print(swift_sum(1, 2))

–EOF–

// 自定义表达式模式
struct Student {
    var score = 0, name = ""
    /// pattern: case 后面内容
    /// value: switch 后面内容
    static func ~=(pattern: Int, value: Student) -> Bool {
        return value.score >= pattern
    }
    static func ~=(pattern: Range<Int>, value: Student) -> Bool {
        return pattern.contains(value.score)
    }
    static func ~=(pattern: ClosedRange<Int>, value: Student) -> Bool {
        return pattern.contains(value.score)
    }
}
var stu = Student(score: 75, name: "Tom")
switch stu {
case 100:
    print(">=100")
case 90:
    print(">=90")
case 80..<90:
    print("[80, 90]")
case 60...79:
    print("[60, 79]")
case 0:
    print(">=0")
default:
    break
}
extension String {
    static func ~=(pattern: (String) -> String, value: String) -> Bool {
        return pattern(value)
    }
}
func hasPrefix(_ prefix: String) -> ((String) -> Bool) {
    return { $0.hasPrefix(prefix) }
}
func hasSuffix(_ suffix: String) -> ((String) -> Bool) {
    return { $0.hasSuffix(suffix) }
}
var fn = hasPrefix("123")
print(fn("123456"))
var str = "123456"
switch str {
case hasPrefix("123"), hasSuffix("456"):
    print("123开头")
    print("456结尾")
default:
    break
}
func isEven(_ i: Int) -> Bool {
    return i % 2 == 0
}
func isOdd(_ i: Int) -> Bool {
    return i % 2 != 0
}
extension Int {
    static func ~=(pattern: (Int) -> Bool, value: Int) -> Bool {
        return pattern(value)
    }
}
var age = 9
switch age {
case isEven: //函数匹配,函数类型
    print(age,"是个偶数")
case isOdd:
    print(age,"是个奇数")
default:
    break
}

–EOF–