swift SIMD。用于对小矢量和矩阵执行计算的模块。

参考:https://developer.apple.com/documentation/accelerate/simd/working_with_vectors

.swift
import simd // importing module

let arr = [2.0, 2.0]
// initializing simd
let vector = simd_double2(x: arr[0], y:arr[1]) // initializing
let normalized_vector = simd_normalize(vector) // normalized vector
let gfd : Double = normalized_vector.x // fetching values

import simd // importing module

let arr = [2.0, 2.0]
// initializing simd
let vector = simd_double2(x: arr[0], y:arr[1]) // initializing
let normalized_vector = simd_normalize(vector) // normalized vector
let gfd : Double = normalized_vector.x // fetching values
let transposed_matrix = simd_double3x3(rows: rows).transpose //transpose of matrix

//*** Multiply vectors -----------
import simd
let rows = [
    simd_double3(2,      0, 0),
    simd_double3(     1, 2, 0),
    simd_double3(     0,      0, 1)
]
let RotationMatrix = simd_double3x3(rows: rows)
let positionVector = simd_double3(x: 3, y: 2, z: 1)
print(RotationMatrix)
print(RotationMatrix*positionVector)
//------------------------------***

//*** Cross multiplication of vectors---------
let two = simd_double3(x: 3, y: 2, z: 12)
let three = simd_double3(x: 14, y: 22, z: 10)
print(cross(two, three))
//-----------------------------------------***

//*** converting matrix into string----------
let RotationMatrix = simd_double3x3(rows: rows)
var rotationMatrix_string = ""
for i in 0...2{
    for col in [RotationMatrix.columns.0, RotationMatrix.columns.1, RotationMatrix.columns.2]
    {
        rotationMatrix_string += String(col[i]) + ", "
    }
    rotationMatrix_string += "\n"
}

rotationMatrix_string
print(rotationMatrix_string)
//---------------------------------------*****


//finding angle between two vectors
import simd
var vector1 = float3(0.0, 1.0, 0.0) // VECTOR 1
var vector2 = float3(1.0, 1.0, 0.0) // VECTOR 2
var dotProduct = dot(vector1, vector2)
var a = dotProduct / (length(vector1) * length(vector2))
a = Float(round(1000*a)/1000)
let angle = acos(a)*(360.0/3.14) // angle is in degrees

//

swift 在数组的每个元素上调用函数

.swift
1. forEach(_:)
  Calls the given closure on each element in the sequence in the same order as a for-in loop.
  
  The two loops in the following example produce the same output:

let numberWords = ["one", "two", "three"]
numberWords.forEach { word in
    print(word)
}
// "one"
// "two"
// "three"

    Using the forEach method is distinct from a for-in loop in two important ways:
    You cannot use a break or continue statement to exit the current call of the body closure or skip subsequent calls.
    Using the return statement in the body closure will exit only from the current call to body, not from any outer scope, and won’t skip subsequent calls.
    
2. Map & CompactMap
let possibleNumbers = ["1", "2", "three", "///4///", "5"]

let mapped: [Int?] = possibleNumbers.map { str in Int(str) }
// [1, 2, nil, nil, 5]

let compactMapped: [Int] = possibleNumbers.compactMap { str in Int(str) }
// [1, 2, 5]

arr = [1,2,3]
print(arr.compactMap { $0/2 })

swift 数组中元素的第一个索引

.swift
var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
    students[i] = "Max"
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"

swift 开始变量

.swift
var arrAccnX = [Double]() // array

swift 三元算子,条件陈述

.swift
carNo== nil ? "," : carNo!.description

swift Double / Int变量的无穷大值

.swift
let maxm_gps_acceleration = -1*Double.infinity // Double
if maxm_gps_acceleration < -1000000
{
    print("done")
}

let max_value: Int64 = Int64.max // Int64

swift swift函数返回两种不同的数据类型

.swift
func findTRMForTW()-> (Bool,[Double])
{
    return (false, [0.0])
}
findTRMForTW()

swift 莫亚第三方范例.swift

Moya.swift
//
//  FMRecommendAPI.swift
//  YYSwiftProject
//
//  Created by Domo on 2018/7/26.
//  Copyright © 2018年 知言网络. All rights reserved.
//

import Foundation
import Moya
import HandyJSON

/// 首页推荐主接口
let FMRecommendProvider = MoyaProvider<FMRecommendAPI>()

enum FMRecommendAPI {
    case recommendList//推荐列表
    case recommendForYouList // 为你推荐
    case recommendAdList // 推荐页面穿插的广告
    case guessYouLikeMoreList // 猜你喜欢更多
    
    case changeGuessYouLikeList // 更换猜你喜欢
    case changePaidCategoryList //更换精品
    case changeLiveList // 更换直播
    case changeOtherCategory(categoryId:Int)// 更换其他
}

extension FMRecommendAPI: TargetType {
    //服务器地址
    public var baseURL: URL {
        switch self {
        case .recommendAdList:
            return URL(string: "http://adse.ximalaya.com")!
        default:
            return URL(string: "http://mobile.ximalaya.com")!
        }
    }

    var path: String {
        switch self {
        case .recommendList: return "/discovery-firstpage/v2/explore/ts-1532411485052"
        case .recommendForYouList: return "/mobile/discovery/v4/recommend/albums"
        case .recommendAdList: return "/ting/feed/ts-1532656780625"
        case .guessYouLikeMoreList: return "/discovery-firstpage/guessYouLike/list/ts-1534815616591"
        case .changeGuessYouLikeList: return "/discovery-firstpage/guessYouLike/cycle/ts-1535167862593"
        case .changePaidCategoryList: return "/mobile/discovery/v1/guessYouLike/paidCategory/ts-1535167980873"
        case .changeLiveList: return "/lamia/v1/hotpage/exchange"
        case .changeOtherCategory: return "/mobile/discovery/v4/albums/ts-1535168024113"
        }
    }

    var method: Moya.Method { return .get }
    var task: Task {
        var parmeters:[String:Any] = [:]
        switch self {
        case .recommendList:
            parmeters = [
                "device":"iPhone",
                            "appid":0,
                            "categoryId":-2,
                            "channel":"ios-b1",
                            "code":"43_310000_3100",
                            "includeActivity":true,
                            "includeSpecial":true,
                            "network":"WIFI",
                            "operator":3,
                            "pullToRefresh":true,
                            "scale":3,
                            "uid":0,
                            "version":"6.5.3",
                            "xt": Int32(Date().timeIntervalSince1970),
                            "deviceId": UIDevice.current.identifierForVendor!.uuidString]
        case .recommendForYouList:
            parmeters = [
                "device":"iPhone",
            "excludedAlbumIds":"3144231%2C3160816%2C5088879%2C3703879%2C9723091%2C12580785%2C12610571%2C13507836%2C11501536%2C12642314%2C4137349%2C10587045%2C6233693%2C4436043%2C16302530%2C15427120%2C13211141%2C61%2C220565%2C3475911%2C3179882%2C10596891%2C261506%2C7183288%2C203355%2C3493173%2C7054736%2C10728301%2C2688602%2C13048404",
                "appid":0,
                "categoryId":-2,
                "pageId":1,
                "pageSize":20,
                "network":"WIFI",
                "operator":3,
                "scale":3,
                "uid":124057809,
                "version":"6.5.3",
                "xt": Int32(Date().timeIntervalSince1970),
                "deviceId": UIDevice.current.identifierForVendor!.uuidString]
            
        case .recommendAdList:
            parmeters = [
                "device":"iPhone",
                "appid":0,
                "name":"find_native",
                "network":"WIFI",
                "operator":3,
                "scale":3,
                "version":"6.5.3",
                "xt": Int32(Date().timeIntervalSince1970)
            ]
            /*
             http://mobile.ximalaya.com/discovery-firstpage/guessYouLike/list/ts-1534815616591?appid=0&device=iPhone&deviceId=5DC0EF2A-01F6-41D1-8455-C4A1BF927E36&inreview=false&network=WIFI&operator=3&pageId=1&pageSize=20&scale=3&uid=124057809&version=6.5.3&xt=1534815616592%20HTTP/1.1
             */
        case .guessYouLikeMoreList:
            parmeters = [
                "device":"iPhone",
                "appid":0,
                "inreview":false,
                "network":"WIFI",
                "operator":3,
                "pageId":1,
                "pageSize":20,
                "scale":3,
                "uid":124057809,
                "version":"6.5.3",
                "xt": Int32(Date().timeIntervalSince1970),
                "deviceId": UIDevice.current.identifierForVendor!.uuidString]
            
        case .changeGuessYouLikeList:
            parmeters = [
                "device":"iPhone",
                "appid":0,
                "excludedAdAlbumIds":"8258116%2C8601255%2C16514340",
                "excludedAlbumIds":"4169245%2C4156778%2C4078652%2C8601255%2C4177638%2C16514340%2C5993267%2C12201334%2C13089888%2C4310827%2C4792267%2C2912127%2C13403391%2C4193171%2C5411224%2C8258116%2C4323493%2C10829913",
                "excludedRoomIds":"",
                "excludedSpecialIds":"",
                
                "excludedOffset":18,
                "inreview":false,
                "loopIndex":3,
                "network":"WIFI",
                "operator":3,
                "pageId":1,
                "pageSize":6,
                "scale":3,
                "uid":0,
                "version":"6.5.3",
                "xt": Int32(Date().timeIntervalSince1970),
                "deviceId": UIDevice.current.identifierForVendor!.uuidString]
            
        case .changePaidCategoryList:
        parmeters = [
            "device":"iPhone",
            "appid":0,
            "excludedAdAlbumIds":13616258,
            "excludedOffset":18,
            "network":"WIFI",
            "operator":3,
            "pageId":1,
            "pageSize":3,
            "scale":3,
            "uid":0,
            "version":"6.5.3",
            "xt": Int32(Date().timeIntervalSince1970),
            "deviceId": UIDevice.current.identifierForVendor!.uuidString]

            
        case .changeLiveList:
            parmeters = [
                "currentRecordIds":"1655918%2C1671613%2C1673030%2C1670774%2C1673082%2C1672407",
                "pageId":1,
                "pageSize":6,
                "device":"iPhone"
            ]
            
        case .changeOtherCategory(let categoryId):
            parmeters = [
                "appid":0,
                "excludedAlbumIds":"7024810%2C8424399%2C8125936",
                "excludedAdAlbumIds":"13616258",
                "excludedOffset":3,
                "network":"WIFI",
                "operator":3,
                "pageId":1,
                "pageSize":3,
                "scale":3,
                "uid":0,
                "version":"6.5.3",
                "xt": Int32(Date().timeIntervalSince1970),
                "deviceId": UIDevice.current.identifierForVendor!.uuidString
            ]
            parmeters["categoryId"] = categoryId
        }
        

        return .requestParameters(parameters: parmeters, encoding: URLEncoding.default)
    }

    var sampleData: Data { return "".data(using: String.Encoding.utf8)! }
    var headers: [String : String]? { return nil }
}

swift 莫亚官方范例.swift

Moya.swift
// swiftlint:disable force_unwrapping

import Foundation
import Moya

// MARK: - Provider setup

private func JSONResponseDataFormatter(_ data: Data) -> Data {
    do {
        let dataAsJSON = try JSONSerialization.jsonObject(with: data)
        let prettyData =  try JSONSerialization.data(withJSONObject: dataAsJSON, options: .prettyPrinted)
        return prettyData
    } catch {
        return data // fallback to original data if it can't be serialized.
    }
}

let gitHubProvider = MoyaProvider<GitHub>(plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)])

// MARK: - Provider support

private extension String {
    var urlEscaped: String {
        return self.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
}

public enum GitHub {
    case zen
    case userProfile(String)
    case userRepositories(String)
}

extension GitHub: TargetType {
    public var baseURL: URL { return URL(string: "https://api.github.com")! }
    public var path: String {
        switch self {
        case .zen:
            return "/zen"
        case .userProfile(let name):
            return "/users/\(name.urlEscaped)"
        case .userRepositories(let name):
            return "/users/\(name.urlEscaped)/repos"
        }
    }
    public var method: Moya.Method {
        return .get
    }
    public var task: Task {
        switch self {
        case .userRepositories:
            return .requestParameters(parameters: ["sort": "pushed"], encoding: URLEncoding.default)
        default:
            return .requestPlain
        }
    }
    public var validationType: ValidationType {
        switch self {
        case .zen:
            return .successCodes
        default:
            return .none
        }
    }
    public var sampleData: Data {
        switch self {
        case .zen:
            return "Half measures are as bad as nothing at all.".data(using: String.Encoding.utf8)!
        case .userProfile(let name):
            return "{\"login\": \"\(name)\", \"id\": 100}".data(using: String.Encoding.utf8)!
        case .userRepositories(let name):
            return "[{\"name\": \"\(name)\"}]".data(using: String.Encoding.utf8)!
        }
    }
    public var headers: [String: String]? {
        return nil
    }
}

public func url(_ route: TargetType) -> String {
    return route.baseURL.appendingPathComponent(route.path).absoluteString
}

// MARK: - Response Handlers

extension Moya.Response {
    func mapNSArray() throws -> NSArray {
        let any = try self.mapJSON()
        guard let array = any as? NSArray else {
            throw MoyaError.jsonMapping(self)
        }
        return array
    }
}

swift 313 && 314 Request.swift

313 314 Request.swift

                        if model.statusCode == 314 || model.statusCode == 313{
                            //Token
                            if model.statusCode == 314{
                                JXNet.tokenLoginNum += 1
                                JXLog(">>>tokenLoginNum:\(JXNet.tokenLoginNum)")
                                
                                if JXNet.tokenLoginNum > 9 {
                                    Consumer.current.logout()
                                    return
                                }
                            }
                            
                            if model.statusCode == 313{
                                let statusCode313 = "statusCode313"
                                if let dictString = (par as NSDictionary).sign() as? [AnyHashable : Any]{
                                    let string = dictString.convertToJSONString()
                                    UserDefaults.standard.set(">>>\(isAbsoluteURL ? "" : Constant.Base.URLString)\(url)" + string, forKey: statusCode313)
                                    let result = (par as NSDictionary).getSignBegin()//内部存储UserDefualts
                                    
                                    BUGReport.reportBugToServer(string: "\(string) \n \(result)")
                                }
                            }
                            
                            //优先尝试校准时间戳, 然后重新拉取用户信息获得Token
                            Date.netTime(successBlock: {
                                Consumer.getToken(update: false, block: {
                                    //在自动登陆成功以后会执行登陆成功推送,在这里断绝首页重新请求的问题,直接返回Error, 如果其他接口也发现类似问题, 直接去除重新请求逻辑
                                    if url == "v5/challenge/selectAllGoingChallenges"{
                                        handler(model)
                                    }else{
                                        JXNet.retryNum += 1
                                        if JXNet.retryNum > 2{
                                            JXNet.retryNum = 0
                                            errorBlock()
                                        }else{//重请求, 此次不再进行返回
                                            JXNet.requestBase(url, par: par, method: method, isJSON: isJSON, isAbsoluteURL: isAbsoluteURL, isDelay: isDelay, timeout: timeout, handler: handler, error: errorBlock)
                                        }
                                    }
                                    NotificationCenter.default.postNotificationOnMainThread(withName: kGETTOKENDONE.rawValue, object: nil, userInfo: ["url" : url])//并没有通知接收者
                                }, fallBlock: {//自动登录失败, 进入登录页面
                                    JXNet.retryNum += 1
                                    if JXNet.retryNum > 2{
                                        JXNet.retryNum = 0
                                        errorBlock()
                                    }else{//重请求, 此次不再进行返回
                                        JXNet.requestBase(url, par: par, method: method, isJSON: isJSON, isAbsoluteURL: isAbsoluteURL, isDelay: isDelay, timeout: timeout, handler: handler, error: errorBlock)
                                    }
                                })
                                SVProgressHUD.dismiss()
                            }, failBlock: {
                                errorBlock()
                                SVProgressHUD.dismiss()
                            })
                            return
                        }