repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mleiv/SerializableData
|
SerializableDataDemo/SerializableDataDemo/Core Data/SimpleCoreDataManager.swift
|
1
|
1853
|
//
// SimpleCoreDataManager.swift
//
// Copyright 2017 Emily Ivie
// Licensed under The MIT License
// For full copyright and license information, please see http://opensource.org/licenses/MIT
// Redistributions of files must retain the above copyright notice.
import CoreData
struct SimpleCoreDataManager: SimpleSerializedCoreDataManageable {
public static let defaultStoreName = "SerializableDataDemo"
public var serializedDataKey: String { return "serializedData" }
public static var current: SimpleCoreDataManager = SimpleCoreDataManager(storeName: defaultStoreName)
public static var isManageMigrations: Bool = true // we manage migrations
public var isConfinedToMemoryStore: Bool = false
public let storeName: String
public let persistentContainer: NSPersistentContainer
public let specificContext: NSManagedObjectContext?
public init() {
self.init(storeName: SimpleCoreDataManager.defaultStoreName)
}
public init(storeName: String?, context: NSManagedObjectContext?, isConfineToMemoryStore: Bool) {
self.storeName = storeName ?? SimpleCoreDataManager.defaultStoreName
self.specificContext = context
if let storeName = storeName {
self.persistentContainer = NSPersistentContainer(name: storeName)
initContainer(isConfineToMemoryStore: isConfineToMemoryStore)
} else {
persistentContainer = SimpleCoreDataManager.current.persistentContainer
}
}
public func runMigrations(storeUrl: URL) {
do {
try MoveStore20170211().run() // special case because I made a dumb mistake
try CoreDataStructuralMigrations(storeName: storeName, storeUrl: storeUrl).run()
} catch {
fatalError("Could not run migrations \(error)")
}
}
}
|
mit
|
3779c81329c6c5fad8e9abf66929f767
| 37.604167 | 105 | 0.716676 | 5.309456 | false | false | false | false |
kickstarter/ios-oss
|
Library/ViewModels/BackingCellViewModel.swift
|
1
|
2661
|
import KsApi
import ReactiveSwift
import UIKit
public protocol BackingCellViewModelInputs {
func configureWith(backing: Backing, project: Project, isFromBacking: Bool)
}
public protocol BackingCellViewModelOutputs {
/// Emits a boolean whether the backing info button is hidden or not.
var backingInfoButtonIsHidden: Signal<Bool, Never> { get }
var pledged: Signal<String, Never> { get }
var reward: Signal<String, Never> { get }
var delivery: Signal<String, Never> { get }
var rootStackViewAlignment: Signal<UIStackView.Alignment, Never> { get }
}
public protocol BackingCellViewModelType {
var inputs: BackingCellViewModelInputs { get }
var outputs: BackingCellViewModelOutputs { get }
}
public final class BackingCellViewModel: BackingCellViewModelType, BackingCellViewModelInputs,
BackingCellViewModelOutputs {
public init() {
let backingAndProjectAndIsFromBacking = self.backingAndProjectAndIsFromBackingProperty.signal.skipNil()
let backing = backingAndProjectAndIsFromBacking.map { $0.0 }
self.backingInfoButtonIsHidden = backingAndProjectAndIsFromBacking
.map { _, _, isFromBacking in isFromBacking }
self.pledged = backingAndProjectAndIsFromBacking.map { backing, project, _ in
Strings.backing_info_pledged_backing_amount(
backing_amount: Format.currency(backing.amount, country: project.country)
)
}
self.reward = backing.map { $0.reward?.description ?? "" }
self.delivery = backing.map { backing in
backing.reward?.estimatedDeliveryOn.map {
Strings.backing_info_estimated_delivery_date(
delivery_date: Format.date(
secondsInUTC: $0,
template: DateFormatter.monthYear,
timeZone: UTCTimeZone
)
)
}
}
.map { $0 ?? "" }
self.rootStackViewAlignment = backingAndProjectAndIsFromBacking
.map { _, _, _ in AppEnvironment.current.isVoiceOverRunning() ? .fill : .leading }
}
fileprivate let backingAndProjectAndIsFromBackingProperty = MutableProperty<(Backing, Project, Bool)?>(nil)
public func configureWith(backing: Backing, project: Project, isFromBacking: Bool) {
self.backingAndProjectAndIsFromBackingProperty.value = (backing, project, isFromBacking)
}
public let backingInfoButtonIsHidden: Signal<Bool, Never>
public let pledged: Signal<String, Never>
public let reward: Signal<String, Never>
public let delivery: Signal<String, Never>
public let rootStackViewAlignment: Signal<UIStackView.Alignment, Never>
public var inputs: BackingCellViewModelInputs { return self }
public var outputs: BackingCellViewModelOutputs { return self }
}
|
apache-2.0
|
0bdff29a6f871e687d35de574a4b70fb
| 36.478873 | 109 | 0.737693 | 4.472269 | false | false | false | false |
marinehero/LeetCode-Solutions-in-Swift
|
Solutions/Solutions/Medium/Medium_078_Subsets.swift
|
4
|
1004
|
/*
https://leetcode.com/problems/subsets/
#78 Subsets
Level: medium
Given a set of distinct integers, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Inspired by @thumike at https://leetcode.com/discuss/9213/my-solution-using-bit-manipulation
*/
import Foundation
struct Medium_078_Subsets {
static func subsets(var nums: [Int]) -> [[Int]] {
nums.sortInPlace {$0 < $1}
let elemNum = nums.count
let subsetNum = Int(pow(2.0, Double(elemNum)))
var subsets: [[Int]] = [[Int]](count: subsetNum, repeatedValue: [])
for var i = 0; i < elemNum; i++ {
for var j = 0; j < subsetNum; j++ {
if ((j >> i) & 1) != 0 {
subsets[j].append(nums[i])
}
}
}
return subsets
}
}
|
mit
|
76fb18add888bdd3638532bf5c268a82
| 19.510204 | 92 | 0.566733 | 3.098765 | false | false | false | false |
radvansky-tomas/NutriFacts
|
nutri-facts/nutri-facts/Libraries/Ex/Float.swift
|
30
|
1595
|
//
// Float.swift
// ExSwift
//
// Created by pNre on 04/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
public extension Float {
/**
Absolute value.
:returns: fabs(self)
*/
func abs () -> Float {
return fabsf(self)
}
/**
Squared root.
:returns: sqrtf(self)
*/
func sqrt () -> Float {
return sqrtf(self)
}
/**
Rounds self to the largest integer <= self.
:returns: floorf(self)
*/
func floor () -> Float {
return floorf(self)
}
/**
Rounds self to the smallest integer >= self.
:returns: ceilf(self)
*/
func ceil () -> Float {
return ceilf(self)
}
/**
Rounds self to the nearest integer.
:returns: roundf(self)
*/
func round () -> Float {
return roundf(self)
}
/**
Clamps self to a specified range.
:param: min Lower bound
:param: max Upper bound
:returns: Clamped value
*/
func clamp (min: Float, _ max: Float) -> Float {
return Swift.max(min, Swift.min(max, self))
}
/**
Random float between min and max (inclusive).
:param: min
:param: max
:returns: Random number
*/
static func random(min: Float = 0, max: Float) -> Float {
let diff = max - min;
let rand = Float(arc4random() % (UInt32(RAND_MAX) + 1))
return ((rand / Float(RAND_MAX)) * diff) + min;
}
}
|
gpl-2.0
|
3ee680c23089e335a33db861479ca765
| 18.216867 | 63 | 0.491536 | 4.007538 | false | false | false | false |
adly-holler/Bond
|
BondTests/UIImageViewTests.swift
|
13
|
670
|
//
// UIImageViewTests.swift
// Bond
//
// Created by Anthony Egerton on 11/03/2015.
// Copyright (c) 2015 Bond. All rights reserved.
//
import UIKit
import XCTest
import Bond
class UIImageViewTests: XCTestCase {
func testUIImageViewBond() {
let image = UIImage()
var dynamicDriver = Dynamic<UIImage?>(nil)
let imageView = UIImageView()
imageView.image = image
XCTAssert(imageView.image == image, "Initial value")
dynamicDriver ->> imageView.designatedBond
XCTAssert(imageView.image == nil, "Value after binding")
imageView.image = image
XCTAssert(imageView.image == image, "Value after dynamic change")
}
}
|
mit
|
89dc99fcaaff360a54db94bcd1549c78
| 22.103448 | 69 | 0.685075 | 4.240506 | false | true | false | false |
codeOfRobin/Components-Personal
|
Sources/TeamPickerViewController.swift
|
1
|
3738
|
//
// TeamPickerViewController.swift
// SearchableComponent
//
// Created by Robin Malhotra on 04/09/17.
// Copyright © 2017 Robin Malhotra. All rights reserved.
//
import AsyncDisplayKit
import RxSwift
import RxCocoa
public class TeamPickerViewController: UIViewController, ASTableDelegate {
let agentsObservable: Observable<[AgentViewModel]>
let onSelectingTeam: (TeamViewModel) -> ()
let onSelectingAgent: (AssigneeViewModel) -> ()
let disposeBag = DisposeBag()
let teamsObservable: Observable<[TeamViewModel]>
let dataSource: DiffableDataSourceAdapter<TeamViewModel>
init(teamsObservable: Observable<[TeamViewModel]>, agentsObservable: Observable<[AgentViewModel]>, onSelectingTeam: @escaping (TeamViewModel) -> (), onSelectingAgent: @escaping (AssigneeViewModel) -> ()) {
self.teamsObservable = teamsObservable
self.onSelectingTeam = onSelectingTeam
self.onSelectingAgent = onSelectingAgent
self.agentsObservable = agentsObservable
self.dataSource = DiffableDataSourceAdapter<TeamViewModel>.init(dataObservable: teamsObservable) { (teamViewModel) -> ASCellNode in
let textNode = ChevronTextNode(text: teamViewModel.label)
return OptionNode(contentNode: textNode)
}
super.init(nibName: nil, bundle: nil)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
let tableNode = ASTableNode()
public override func viewDidLoad() {
super.viewDidLoad()
self.title = "Assignee"
tableNode.dataSource = dataSource
dataSource.tableNode = tableNode
tableNode.delegate = self
tableNode.view.tableFooterView = UIView()
self.view.addSubnode(tableNode)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: FrameworkImage.close, style: .plain, target: self, action: #selector(closeButtonPressed))
if #available(iOS 11.0, *) {
let searchDataObservable = PublishSubject<[AgentViewModel]>()
let searchDataSource = DiffableDataSourceAdapter<AgentViewModel>(dataObservable: searchDataObservable.asObservable()) { (agent) -> ASCellNode in
return OptionNode(contentNode: AgentCellNode(agentViewModel: agent))
}
let searchResultsController = SingleSelectViewController(dataSource: searchDataSource, title: "Agents", onSelecting: { [weak self] (agent) in
self?.onSelectingAgent(.agent(agent))
})
let searchController = UISearchController(searchResultsController: searchResultsController)
searchController.obscuresBackgroundDuringPresentation = true
self.definesPresentationContext = true
self.navigationItem.searchController = searchController
self.navigationItem.hidesSearchBarWhenScrolling = false
Observable.combineLatest(searchController.searchBar.rx.text, agentsObservable).map {
text, agents -> [AgentViewModel] in
guard let text = text else { return []}
// let array = agents.sorted(by: { (agent1, agent2) -> Bool in
// //confidenceScore is 1.0 if no match
// agent1.agentName.confidenceScore(text) ?? 2.0 < agent2.agentName.confidenceScore(text) ?? 2.0
// })
// return Array(array.prefix(10))
return agents.filter { (agent) -> Bool in
return agent.agentName.contains(text)
}
}.bind(to: searchDataObservable).disposed(by: disposeBag)
} else {
// Fallback on earlier versions
}
}
@objc func closeButtonPressed() {
self.dismiss(animated: true, completion: nil)
}
public func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
tableNode.deselectRow(at: indexPath, animated: true)
onSelectingTeam(dataSource.dataVariable.value[indexPath.row])
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
tableNode.frame = view.frame
}
}
|
mit
|
6ba11ac16c56e1e5542d4fa3737099e3
| 36 | 206 | 0.753546 | 4.213078 | false | false | false | false |
lokinfey/MyPerfectframework
|
PerfectLib/WebRequest.swift
|
2
|
13700
|
//
// WebRequest.swift
// PerfectLib
//
// Created by Kyle Jessup on 7/6/15.
// Copyright (C) 2015 PerfectlySoft, Inc.
//
//===----------------------------------------------------------------------===//
//
// This source file is part of the Perfect.org open source project
//
// Copyright (c) 2015 - 2016 PerfectlySoft Inc. and the Perfect project authors
// Licensed under Apache License v2.0
//
// See http://perfect.org/licensing.html for license information
//
//===----------------------------------------------------------------------===//
//
/// Provides access to all incoming request data. Handles the following tasks:
/// - Parsing the incoming HTTP request
/// - Providing access to all HTTP headers & cookies
/// - Providing access to all meta headers which may have been added by the web server
/// - Providing access to GET & POST arguments
/// - Providing access to any file upload data
/// - Establishing the document root, from which response files are located
///
/// Access to the current WebRequest object is generally provided through the corresponding WebResponse object
public class WebRequest {
var connection: WebConnection
public lazy var documentRoot: String = {
var f = self.connection.requestParams["PERFECTSERVER_DOCUMENT_ROOT"]
var root = ""
if let r = f {
root = r
} else {
f = self.connection.requestParams["DOCUMENT_ROOT"]
if let r = f {
root = r
}
}
return root
}()
private var cachedHttpAuthorization: [String:String]? = nil
/// Variables set by the URL routing process
public lazy var urlVariables = [String:String]()
/// A `Dictionary` containing all HTTP header names and values
/// Only HTTP headers are included in the result. Any "meta" headers, i.e. those provided by the web server, are discarded.
public lazy var headers: [String:String] = {
var d = Dictionary<String, String>()
for (key, value) in self.connection.requestParams {
if key.hasPrefix("HTTP_") {
let utf16 = key.utf16
let index = key.utf16.startIndex.advancedBy(5)
let nKey = String(key.utf16.suffixFrom(index))!
d[nKey.stringByReplacingString("_", withString: "-")] = value
}
}
return d
}()
/// A tuple array containing each incoming cookie name/value pair
public lazy var cookies: [(String, String)] = {
var c = [(String, String)]()
let rawCookie = self.httpCookie()
let semiSplit = rawCookie.characters.split(";").map { String($0.filter { $0 != " " }) }
for cookiePair in semiSplit {
let cookieSplit = cookiePair.characters.split("=", allowEmptySlices: true).map { String($0.filter { $0 != " " }) }
if cookieSplit.count == 2 {
let name = cookieSplit[0].stringByDecodingURL
let value = cookieSplit[1].stringByDecodingURL
if let n = name {
c.append((n, value ?? ""))
}
}
}
return c
}()
/// A tuple array containing each GET/search/query parameter name/value pair
public lazy var queryParams: [(String, String)] = {
var c = [(String, String)]()
let qs = self.queryString()
let semiSplit = qs.characters.split("&").map { String($0) }
for paramPair in semiSplit {
let paramSplit = paramPair.characters.split("=", allowEmptySlices: true).map { String($0) }
if paramSplit.count == 2 {
let name = paramSplit[0].stringByDecodingURL
let value = paramSplit[1].stringByDecodingURL
if let n = name {
c.append((n, value ?? ""))
}
}
}
return c
}()
/// An array of `MimeReader.BodySpec` objects which provide access to each file which was uploaded
public lazy var fileUploads: [MimeReader.BodySpec] = {
var c = Array<MimeReader.BodySpec>()
if let mime = self.connection.mimes {
for body in mime.bodySpecs {
if body.file != nil {
c.append(body)
}
}
}
return c
}()
/// Return the raw POST body as a byte array
/// This is mainly useful when POSTing non-url-encoded and not-multipart form data
/// For example, if the content-type were application/json you could use this function to get the raw JSON data as bytes
public lazy var postBodyBytes: [UInt8] = {
if let stdin = self.connection.stdin {
return stdin
}
return [UInt8]()
}()
/// Return the raw POST body as a String
/// This is mainly useful when POSTing non-url-encoded and not-multipart form data
/// For example, if the content-type were application/json you could use this function to get the raw JSON data as a String
public lazy var postBodyString: String = {
if let stdin = self.connection.stdin {
let qs = UTF8Encoding.encode(stdin)
return qs
}
return ""
}()
/// A tuple array containing each POST parameter name/value pair
public lazy var postParams: [(String, String)] = {
var c = [(String, String)]()
if let mime = self.connection.mimes {
for body in mime.bodySpecs {
if body.file == nil {
c.append((body.fieldName, body.fieldValue))
}
}
} else if let stdin = self.connection.stdin {
let qs = UTF8Encoding.encode(stdin)
let semiSplit = qs.characters.split("&").map { String($0) }
for paramPair in semiSplit {
let paramSplit = paramPair.characters.split("=", allowEmptySlices: true).map { String($0) }
if paramSplit.count == 2 {
let name = paramSplit[0].stringByReplacingString("+", withString: " ").stringByDecodingURL
let value = paramSplit[1].stringByReplacingString("+", withString: " ").stringByDecodingURL
if let n = name {
c.append((n, value ?? ""))
}
}
}
}
return c
}()
/// Returns the first GET or POST parameter with the given name
public func param(name: String) -> String? {
for p in self.queryParams
where p.0 == name {
return p.1
}
for p in self.postParams
where p.0 == name {
return p.1
}
return nil
}
/// Returns the first GET or POST parameter with the given name
/// Returns the supplied default value if the parameter was not found
public func param(name: String, defaultValue: String) -> String {
for p in self.queryParams
where p.0 == name {
return p.1
}
for p in self.postParams
where p.0 == name {
return p.1
}
return defaultValue
}
/// Returns all GET or POST parameters with the given name
public func params(named: String) -> [String]? {
var a = [String]()
for p in self.queryParams
where p.0 == named {
a.append(p.1)
}
for p in self.postParams
where p.0 == named {
a.append(p.1)
}
return a.count > 0 ? a : nil
}
/// Returns all GET or POST parameters
public func params() -> [(String,String)]? {
var a = [(String,String)]()
for p in self.queryParams {
a.append(p)
}
for p in self.postParams {
a.append(p)
}
return a.count > 0 ? a : nil
}
/// Provides access to the HTTP_CONNECTION parameter.
public func httpConnection() -> String { return connection.requestParams["HTTP_CONNECTION"] ?? "" }
/// Provides access to the HTTP_COOKIE parameter.
public func httpCookie() -> String { return connection.requestParams["HTTP_COOKIE"] ?? "" }
/// Provides access to the HTTP_HOST parameter.
public func httpHost() -> String { return connection.requestParams["HTTP_HOST"] ?? "" }
/// Provides access to the HTTP_USER_AGENT parameter.
public func httpUserAgent() -> String { return connection.requestParams["HTTP_USER_AGENT"] ?? "" }
/// Provides access to the HTTP_CACHE_CONTROL parameter.
public func httpCacheControl() -> String { return connection.requestParams["HTTP_CACHE_CONTROL"] ?? "" }
/// Provides access to the HTTP_REFERER parameter.
public func httpReferer() -> String { return connection.requestParams["HTTP_REFERER"] ?? "" }
/// Provides access to the HTTP_REFERER parameter but using the proper "referrer" spelling for pedants.
public func httpReferrer() -> String { return connection.requestParams["HTTP_REFERER"] ?? "" }
/// Provides access to the HTTP_ACCEPT parameter.
public func httpAccept() -> String { return connection.requestParams["HTTP_ACCEPT"] ?? "" }
/// Provides access to the HTTP_ACCEPT_ENCODING parameter.
public func httpAcceptEncoding() -> String { return connection.requestParams["HTTP_ACCEPT_ENCODING"] ?? "" }
/// Provides access to the HTTP_ACCEPT_LANGUAGE parameter.
public func httpAcceptLanguage() -> String { return connection.requestParams["HTTP_ACCEPT_LANGUAGE"] ?? "" }
/// Provides access to the HTTP_AUTHORIZATION with all elements having been parsed using the `String.parseAuthentication` extension function.
public func httpAuthorization() -> [String:String] {
guard cachedHttpAuthorization == nil else {
return cachedHttpAuthorization!
}
let auth = connection.requestParams["HTTP_AUTHORIZATION"] ?? connection.requestParams["Authorization"] ?? ""
var ret = auth.parseAuthentication()
if ret.count > 0 {
ret["method"] = self.requestMethod()
}
self.cachedHttpAuthorization = ret
return ret
}
/// Provides access to the CONTENT_LENGTH parameter.
public func contentLength() -> Int { return Int(connection.requestParams["CONTENT_LENGTH"] ?? "0") ?? 0 }
/// Provides access to the CONTENT_TYPE parameter.
public func contentType() -> String { return connection.requestParams["CONTENT_TYPE"] ?? "" }
/// Provides access to the PATH parameter.
public func path() -> String { return connection.requestParams["PATH"] ?? "" }
/// Provides access to the PATH_TRANSLATED parameter.
public func pathTranslated() -> String { return connection.requestParams["PATH_TRANSLATED"] ?? "" }
/// Provides access to the QUERY_STRING parameter.
public func queryString() -> String { return connection.requestParams["QUERY_STRING"] ?? "" }
/// Provides access to the REMOTE_ADDR parameter.
public func remoteAddr() -> String { return connection.requestParams["REMOTE_ADDR"] ?? "" }
/// Provides access to the REMOTE_PORT parameter.
public func remotePort() -> Int { return Int(connection.requestParams["REMOTE_PORT"] ?? "0") ?? 0 }
/// Provides access to the REQUEST_METHOD parameter.
public func requestMethod() -> String { return connection.requestParams["REQUEST_METHOD"] ?? "" }
/// Provides access to the REQUEST_URI parameter.
public func requestURI() -> String { return connection.requestParams["REQUEST_URI"] ?? "" }
/// Provides access to the SCRIPT_FILENAME parameter.
public func scriptFilename() -> String { return connection.requestParams["SCRIPT_FILENAME"] ?? "" }
/// Provides access to the SCRIPT_NAME parameter.
public func scriptName() -> String { return connection.requestParams["SCRIPT_NAME"] ?? "" }
/// Provides access to the SCRIPT_URI parameter.
public func scriptURI() -> String { return connection.requestParams["SCRIPT_URI"] ?? "" }
/// Provides access to the SCRIPT_URL parameter.
public func scriptURL() -> String { return connection.requestParams["SCRIPT_URL"] ?? "" }
/// Provides access to the SERVER_ADDR parameter.
public func serverAddr() -> String { return connection.requestParams["SERVER_ADDR"] ?? "" }
/// Provides access to the SERVER_ADMIN parameter.
public func serverAdmin() -> String { return connection.requestParams["SERVER_ADMIN"] ?? "" }
/// Provides access to the SERVER_NAME parameter.
public func serverName() -> String { return connection.requestParams["SERVER_NAME"] ?? "" }
/// Provides access to the SERVER_PORT parameter.
public func serverPort() -> Int { return Int(connection.requestParams["SERVER_PORT"] ?? "0") ?? 0 }
/// Provides access to the SERVER_PROTOCOL parameter.
public func serverProtocol() -> String { return connection.requestParams["SERVER_PROTOCOL"] ?? "" }
/// Provides access to the SERVER_SIGNATURE parameter.
public func serverSignature() -> String { return connection.requestParams["SERVER_SIGNATURE"] ?? "" }
/// Provides access to the SERVER_SOFTWARE parameter.
public func serverSoftware() -> String { return connection.requestParams["SERVER_SOFTWARE"] ?? "" }
/// Provides access to the PATH_INFO parameter if it exists or else the SCRIPT_NAME parameter.
public func pathInfo() -> String { return connection.requestParams["PATH_INFO"] ?? connection.requestParams["SCRIPT_NAME"] ?? "" }
/// Provides access to the GATEWAY_INTERFACE parameter.
public func gatewayInterface() -> String { return connection.requestParams["GATEWAY_INTERFACE"] ?? "" }
/// Returns true if the request was encrypted over HTTPS.
public func isHttps() -> Bool { return connection.requestParams["HTTPS"] ?? "" == "on" }
/// Returns the indicated HTTP header.
public func header(named: String) -> String? { return self.headers[named.uppercaseString] }
/// Returns the raw request parameter header
public func rawHeader(named: String) -> String? { return self.connection.requestParams[named] }
/// Returns a Dictionary containing all raw request parameters.
public func raw() -> Dictionary<String, String> { return self.connection.requestParams }
public func setRequestMethod(method: String) {
connection.requestParams["REQUEST_METHOD"] = method
}
public func setRequestURI(uri: String) {
connection.requestParams["REQUEST_URI"] = uri
}
internal init(_ c: WebConnection) {
self.connection = c
}
private func extractField(from: String, named: String) -> String? {
guard let range = from.rangeOf(named + "=") else {
return nil
}
var currPos = range.endIndex
var ret = ""
let quoted = from[currPos] == "\""
if quoted {
currPos = currPos.successor()
let tooFar = from.endIndex
while currPos != tooFar {
if from[currPos] == "\"" {
break
}
ret.append(from[currPos])
currPos = currPos.successor()
}
} else {
let tooFar = from.endIndex
while currPos != tooFar {
if from[currPos] == "," {
break
}
ret.append(from[currPos])
currPos = currPos.successor()
}
}
return ret
}
}
|
apache-2.0
|
403aa59eefc3156e55ab2a4c39365347
| 36.950139 | 142 | 0.680876 | 3.738063 | false | false | false | false |
duycao2506/SASCoffeeIOS
|
SAS Coffee/Services/LangService.swift
|
1
|
667
|
//
// LangService.swift
// SAS Coffee
//
// Created by Duy Cao on 9/1/17.
// Copyright © 2017 Duy Cao. All rights reserved.
//
import UIKit
class LangService: NSObject {
private override init (){
}
private static var instance : DefaultString!
private static var langName : LangName = .EN
class func shareInstance() -> DefaultString {
if instance == nil {
instance = DefaultString.init()
}
return instance
}
class func changeLang(lang : LangName){
instance = (GlobalUtils.stringClassFromString(lang.rawValue) as! DefaultString.Type).init()
}
}
|
gpl-3.0
|
a6ba9a2e7b99c776ef48cb0209d0fc81
| 18.588235 | 99 | 0.600601 | 4.296774 | false | false | false | false |
mindbody/Conduit
|
Sources/Conduit/Auth/Cryptography/Errors/CryptorError+Codes.swift
|
1
|
1955
|
//
// CryptoError+Codes.swift
// Conduit
//
// Created by John Hammerlund on 12/10/19.
//
import Foundation
extension CryptoError.Code {
/// An internal error occurred during the crypto operation
public static let internalOperationFailed = CryptoError.Code(rawValue: -100)
/// An error occurred while attempting to encrypt the plaintext
public static let encryptionFailed = CryptoError.Code(rawValue: -101)
/// An error occurred while attempting to decrypt the ciphertext
public static let decryptionFailed = CryptoError.Code(rawValue: -102)
/// The requested crypto operation / algorithm is not supported on this device
public static let cryptoOperationUnsupported = CryptoError.Code(rawValue: -103)
/// An error occured while attempting to generate a crypto key
public static let keyGenerationFailed = CryptoError.Code(rawValue: -104)
/// The crypto operation was supplied insufficient or invalid parameters
public static let invalidParameters = CryptoError.Code(rawValue: -105)
}
extension CryptoError.Code {
var defaultMessage: String {
switch self {
case .internalOperationFailed:
return "An internal error occurred during the crypto operation."
case .encryptionFailed:
return "An error occurred while attempting to encrypt the plaintext."
case .decryptionFailed:
return "An error occurred while attempting to decrypt the ciphertext."
case .cryptoOperationUnsupported:
return "The requested crypto operation / algorithm is not supported on this device."
case .keyGenerationFailed:
return "An error occured while attempting to generate a crypto key."
case .invalidParameters:
return "The crypto operation was supplied insufficient or invalid parameters"
default:
return "An unknown error occurred during the crypto operation."
}
}
}
|
apache-2.0
|
7473281a310c260f703c33539fd38c5f
| 43.431818 | 96 | 0.714578 | 5.158311 | false | false | false | false |
MatiasGinart/sdk-ios
|
MercadoPagoSDK/MercadoPagoSDK/CongratsViewController.swift
|
1
|
7877
|
//
// CongratsViewController.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 11/3/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import Foundation
import UIKit
public class CongratsViewController : UIViewController, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate {
var payment: Payment!
var paymentMethod: PaymentMethod!
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var lblDescription: UILabel!
var paymentTotalCell : PaymentTotalTableViewCell!
var congratsPaymentMethodCell : CongratsPaymentMethodTableViewCell!
var paymentIDCell : PaymentIDTableViewCell!
var paymentDateCell : PaymentDateTableViewCell!
var bundle : NSBundle? = MercadoPago.getBundle()
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(payment: Payment, paymentMethod: PaymentMethod) {
super.init(nibName: "CongratsViewController", bundle: bundle)
self.payment = payment
self.paymentMethod = paymentMethod
}
override public func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
declareAndInitCells()
// Title
_setTitle(payment!)
// Icon
_setIcon(payment!)
// Description
setDescription(payment!)
// Amount
setAmount(payment!)
// payment id
setPaymentId(payment!)
// payment method description
setPaymentMethodDescription(payment!)
// payment creation date
setDateCreated(payment!)
// Button text
setButtonText(payment!)
self.tableView.reloadData()
}
public func declareAndInitCells() {
self.tableView.registerNib(UINib(nibName: "PaymentTotalTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "paymentTotalCell")
self.paymentTotalCell = self.tableView.dequeueReusableCellWithIdentifier("paymentTotalCell") as! PaymentTotalTableViewCell
self.tableView.registerNib(UINib(nibName: "CongratsPaymentMethodTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "congratsPaymentMethodCell")
self.congratsPaymentMethodCell = self.tableView.dequeueReusableCellWithIdentifier("congratsPaymentMethodCell") as! CongratsPaymentMethodTableViewCell
self.tableView.registerNib(UINib(nibName: "PaymentIDTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "paymentIDCell")
self.paymentIDCell = self.tableView.dequeueReusableCellWithIdentifier("paymentIDCell") as! PaymentIDTableViewCell
self.tableView.registerNib(UINib(nibName: "PaymentDateTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "paymentDateCell")
self.paymentDateCell = self.tableView.dequeueReusableCellWithIdentifier("paymentDateCell") as! PaymentDateTableViewCell
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.row == 0 {
return self.paymentTotalCell
} else if indexPath.row == 1 {
return self.congratsPaymentMethodCell
} else if indexPath.row == 2 {
return self.paymentIDCell
} else if indexPath.row == 3 {
return self.paymentDateCell
}
return UITableViewCell()
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 60
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
public func _setTitle(payment: Payment) {
if payment.status == "approved" {
self.lblTitle.text = "¡Felicitaciones!".localized
} else if payment.status == "pending" {
self.lblTitle.text = "Se aprobó tu pago.".localized
} else if payment.status == "in_process" {
self.lblTitle.text = "Estamos procesando el pago".localized
} else if payment.status == "rejected" {
self.lblTitle.text = "¡Ups! Ocurrió un problema".localized
}
}
public func _setIcon(payment: Payment) {
if payment.status == "approved" {
self.icon.image = UIImage(named:"ic_approved", inBundle: bundle, compatibleWithTraitCollection:nil)
} else if payment.status == "pending" {
self.icon.image = UIImage(named:"ic_pending", inBundle: bundle, compatibleWithTraitCollection:nil)
} else if payment.status == "in_process" {
self.icon.image = UIImage(named:"ic_pending", inBundle: bundle, compatibleWithTraitCollection:nil)
} else if payment.status == "rejected" {
self.icon.image = UIImage(named:"ic_rejected", inBundle: bundle, compatibleWithTraitCollection:nil)
}
}
public func setDescription(payment: Payment) {
if payment.status == "approved" {
self.lblDescription.text = "Se aprobó tu pago.".localized
} else if payment.status == "pending" {
self.lblDescription.text = "Imprime el cupón y paga. Se acreditará en 1 a 3 días hábiles.".localized
} else if payment.status == "in_process" {
self.lblDescription.text = "En unos minutos te enviaremos por e-mail el resultado.".localized
} else if payment.status == "rejected" {
self.lblDescription.text = "No se pudo realizar el pago.".localized
}
}
public func setAmount(payment: Payment) {
if payment.currencyId != nil {
let formattedAmount : String? = CurrenciesUtil.formatNumber(payment.transactionDetails.totalPaidAmount, currencyId: payment.currencyId)
if formattedAmount != nil {
self.paymentTotalCell.lblTotal.text = formattedAmount
}
}
}
public func setPaymentId(payment: Payment) {
self.paymentIDCell!.lblID.text = String(payment._id)
}
public func setPaymentMethodDescription(payment: Payment) {
if payment.card != nil && payment.card.paymentMethod != nil {
self.congratsPaymentMethodCell!.lblPaymentInfo.text = "terminada en".localized + " " + payment.card!.lastFourDigits!
self.congratsPaymentMethodCell.imgPayment.image = UIImage(named: "icoTc_" + payment.card!.paymentMethod!._id, inBundle: bundle, compatibleWithTraitCollection:nil)
} else if self.paymentMethod != nil {
self.congratsPaymentMethodCell!.lblPaymentInfo.text = self.paymentMethod!.name
self.congratsPaymentMethodCell.imgPayment.image = UIImage(named: "icoTc_" + self.paymentMethod._id, inBundle: bundle, compatibleWithTraitCollection:nil)
}
}
public func setDateCreated(payment: Payment) {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
self.paymentDateCell.lblDate.text = dateFormatter.stringFromDate(payment.dateCreated!)
}
public func setButtonText(payment: Payment) {
var title = "Imprimir cupón".localized
if payment.status == "pending" {
// TODO couponUrl = payment.transactionDetails.externalResourceUrl
} else {
title = "Continuar".localized
// TODO couponUrl = nil
}
self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: title, style: UIBarButtonItemStyle.Plain, target: self, action: "submitForm")
}
public func submitForm() {
self.navigationController?.popToRootViewControllerAnimated(true)
}
}
|
mit
|
407cb0c5fc84a9d98045a045445b4e93
| 40.851064 | 174 | 0.665438 | 4.91995 | false | false | false | false |
mcrollin/S2Geometry
|
Sources/R2/R2Point.swift
|
1
|
2545
|
//
// R2Point.swift
// S2Geometry
//
// Created by Marc Rollin on 4/9/17.
// Copyright © 2017 Marc Rollin. All rights reserved.
//
import Foundation
/// R2Point represents a point in ℝ².
struct R2Point {
let x: Double
let y: Double
}
// MARK: CustomStringConvertible compliance
extension R2Point: CustomStringConvertible {
var description: String {
return "(\(x.debugDescription), \(y.debugDescription))"
}
}
// MARK: Equatable compliance
extension R2Point: Equatable {
/// - returns: true iff both points have similar x and y.
static func == (lhs: R2Point, rhs: R2Point) -> Bool {
return lhs.x == rhs.x && lhs.y == rhs.y
}
}
// MARK: AlmostEquatable compliance
extension R2Point: AlmostEquatable {
/// - returns: true if the x and y are the same up to the given tolerance.
static func ==~ (lhs: R2Point, rhs: R2Point) -> Bool {
return lhs.x ==~ rhs.x && lhs.y ==~ lhs.y
}
}
// MARK: Arithmetic operators
extension R2Point {
/// - returns: the sum of two points.
static func + (lhs: R2Point, rhs: R2Point) -> R2Point {
return R2Point(x: lhs.x + rhs.x, y: lhs.y + rhs.y)
}
/// - returns: the difference between two points.
static func - (lhs: R2Point, rhs: R2Point) -> R2Point {
return R2Point(x: lhs.x - rhs.x, y: lhs.y - rhs.y)
}
/// - returns: the scalar product with a Double.
static func * (lhs: R2Point, rhs: Double) -> R2Point {
return R2Point(x: lhs.x * rhs, y: lhs.y * rhs)
}
static func * (lhs: Double, rhs: R2Point) -> R2Point {
return rhs * lhs
}
/// - returns: the scalar division of two points.
static func / (lhs: R2Point, rhs: Double) -> R2Point {
return lhs * (1 / rhs)
}
}
// MARK: Instance methods and computed properties
extension R2Point {
/// The vector's normal.
var normal: Double {
return hypot(x, y)
}
/// A unit point in the same direction.
var normalized: R2Point {
if x == 0 && x == 0 {
return self
}
return self / normal
}
/// Counterclockwise orthogonal point with the same normal.
var orthogonal: R2Point {
return R2Point(x: -y, y: x)
}
/// - returns: the dot product with point.
func dotProduct(with point: R2Point) -> Double {
return x * point.x + y * point.y
}
/// - returns: the cross product with point.
func crossProduct(with point: R2Point) -> Double {
return x * point.y - y * point.x
}
}
|
mit
|
c3896f17967267054f56536a6e5cb17f
| 23.911765 | 78 | 0.596616 | 3.447761 | false | false | false | false |
ocrickard/Theodolite
|
Theodolite/View/Configuration/ViewConfiguration.swift
|
1
|
2137
|
//
// View.swift
// components-swift
//
// Created by Oliver Rickard on 10/9/17.
// Copyright © 2017 Oliver Rickard. All rights reserved.
//
import UIKit
public class ViewConfiguration: Equatable, Hashable {
let view: UIView.Type
let attributes: [Attribute]
private let hash: Int
public init(view: UIView.Type, attributes: [Attribute]) {
self.view = view
self.attributes = attributes
assert(findDuplicates(attributes: attributes).count == 0,
"Duplicate attributes. You must provide identifiers for: \(findDuplicates(attributes: attributes))")
// Pre-compute hash since it gets called constantly
var hasher = Hasher()
hasher.combine(view.hash())
for attr in attributes {
hasher.combine(attr)
}
self.hash = hasher.finalize()
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.hash)
}
func applyToView(v: UIView) {
assert(type(of: v) == view)
let appliedAttributes: ViewConfiguration? = getAssociatedObject(object: v,
associativeKey: &kAppliedAttributesKey)
if appliedAttributes == self {
return
}
if let needsUnapplication = appliedAttributes {
for attr in needsUnapplication.attributes {
attr.unapply(view: v)
}
}
for attr in self.attributes {
attr.apply(view: v)
}
setAssociatedObject(object: v,
value: self,
associativeKey: &kAppliedAttributesKey)
}
func buildView() -> UIView {
let v = self.view.init()
self.applyToView(v: v)
return v
}
}
public func ==(lhs: ViewConfiguration, rhs: ViewConfiguration) -> Bool {
return lhs.view === rhs.view
&& lhs.attributes == rhs.attributes
}
private func findDuplicates(attributes: [Attribute]) -> [Attribute] {
var set: Set<Attribute> = Set()
var duplicates: [Attribute] = []
for attr in attributes {
if set.contains(attr) {
duplicates.append(attr)
} else {
set.insert(attr);
}
}
return duplicates
}
var kAppliedAttributesKey: Void?
|
mit
|
6df5b90a1ed16b99fdeb3a70d6dbc01a
| 25.37037 | 111 | 0.628745 | 4.180039 | false | false | false | false |
benshan/swift-compiler-crashes
|
crashes-duplicates/06638-getselftypeforcontainer.swift
|
11
|
2531
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let a {
struct d
var d {
struct c<Int>
"\() -> {
var d {
typealias e : Bool)
protocol b : b
protocol b : d {
class d
typealias e : a {
class d<T where S
for c : a {
struct c<T where S<T where S<l : Bool)
typealias b : d
typealias e : d<T where h: Int = compose() -> {
var e
class B<T where B : A
class B<T where T.b : d<l : d {
protocol b : d
let v: A
typealias b : P {
func b: A
func a<T where B {
typealias e : NSObject {
var e
for c : S
protocol B : P {
class B<T where B {
let g = c<T where S<T where T>
class B {
struct c<T where B : P {
let g = f
struct S
typealias e : B<T where h: d {
protocol A {
let a {
"\(t: A? {
class B<T where T>
func a<T where B {
for c : d
protocol B : B<T where T: e: d {
if true {
typealias b : P {
class d
class A {
protocol A {
class B : a {
for c : A : d {
class d<l : b: A? {
for c : d {
let g = f
class B<l : d
func b
struct B<T where T.b : A? {
if true {
func a<Int>
protocol A {
var d {
struct d<l : a {
protocol A {
let g = f
struct d<T where I.b : Bool)
let a {
let a {
protocol B : b
func b
let a {
struct S<T.b : P {
func a<T where S<T where I.b : e
func a<T.b : a {
class B {
class A : b
struct S
protocol A {
enum a<Int>
let v: b
class B : B<T>
protocol B {
protocol A {
struct B<T.b : Int = compose() -> {
if true {
protocol A : S
for c : d {
protocol A : Bool)
class B<T where T>: NSObject {
var d {
class A : P {
var d {
struct d
let v: b
class d<T where S<T where B {
protocol B {
for c : B<T where h: a {
"\() -> {
let a {
for c : b
let v: P {
class d<Int>: P {
protocol B : S<T where I.b : d<T where h: S<T where S<Int>
struct d<T where T: Int = c<T where B {
protocol b : d {
typealias b : d {
class B {
var e
for c : B<T where h: S
protocol A : A? {
enum a<T where B {
struct c<T where T>: A
for c : B<T where S<Int>: A {
let g = compose() -> {
func a<T: A? {
struct c<T>
let g = compose() -> {
struct S<T: A {
"\(t: P {
protocol B : e
class A : d {
protocol B {
protocol b : NSObject {
typealias b : a {
struct c<T where T: d {
var d {
class B : S
struct c<T where S
let a {
protocol A : P {
let v: b: a {
let g = compose() -> {
func b
class B : Int = f
struct d<T where I.Element == f
class d<l : d {
enum a<T where S
struct B<T where B : Int = compose() -> {
protocol b : a {
if true {
struct S
struct B<Int>
func a<T>
class A {
class B : A {
class B {
if true {
class A : NSObject {
let g = compose(t:
|
mit
|
bdc3909969deb820dd90988f8a988e1a
| 15.873333 | 87 | 0.604504 | 2.505941 | false | false | false | false |
jmgc/swift
|
stdlib/public/core/Integers.swift
|
1
|
140651
|
//===--- Integers.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//===--- Bits for the Stdlib ----------------------------------------------===//
//===----------------------------------------------------------------------===//
// FIXME(integers): This should go in the stdlib separately, probably.
extension ExpressibleByIntegerLiteral
where Self: _ExpressibleByBuiltinIntegerLiteral {
@_transparent
public init(integerLiteral value: Self) {
self = value
}
}
//===----------------------------------------------------------------------===//
//===--- AdditiveArithmetic -----------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A type with values that support addition and subtraction.
///
/// The `AdditiveArithmetic` protocol provides a suitable basis for additive
/// arithmetic on scalar values, such as integers and floating-point numbers,
/// or vectors. You can write generic methods that operate on any numeric type
/// in the standard library by using the `AdditiveArithmetic` protocol as a
/// generic constraint.
///
/// The following code declares a method that calculates the total of any
/// sequence with `AdditiveArithmetic` elements.
///
/// extension Sequence where Element: AdditiveArithmetic {
/// func sum() -> Element {
/// return reduce(.zero, +)
/// }
/// }
///
/// The `sum()` method is now available on any sequence with values that
/// conform to `AdditiveArithmetic`, whether it is an array of `Double` or a
/// range of `Int`.
///
/// let arraySum = [1.1, 2.2, 3.3, 4.4, 5.5].sum()
/// // arraySum == 16.5
///
/// let rangeSum = (1..<10).sum()
/// // rangeSum == 45
///
/// Conforming to the AdditiveArithmetic Protocol
/// =============================================
///
/// To add `AdditiveArithmetic` protocol conformance to your own custom type,
/// implement the required operators, and provide a static `zero` property
/// using a type that can represent the magnitude of any value of your custom
/// type.
public protocol AdditiveArithmetic: Equatable {
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
static var zero: Self { get }
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
static func +(lhs: Self, rhs: Self) -> Self
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
static func +=(lhs: inout Self, rhs: Self)
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
static func -(lhs: Self, rhs: Self) -> Self
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
static func -=(lhs: inout Self, rhs: Self)
}
public extension AdditiveArithmetic {
@_alwaysEmitIntoClient
static func +=(lhs: inout Self, rhs: Self) {
lhs = lhs + rhs
}
@_alwaysEmitIntoClient
static func -=(lhs: inout Self, rhs: Self) {
lhs = lhs - rhs
}
}
public extension AdditiveArithmetic where Self: ExpressibleByIntegerLiteral {
/// The zero value.
///
/// Zero is the identity element for addition. For any value,
/// `x + .zero == x` and `.zero + x == x`.
@inlinable @inline(__always)
static var zero: Self {
return 0
}
}
//===----------------------------------------------------------------------===//
//===--- Numeric ----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// A type with values that support multiplication.
///
/// The `Numeric` protocol provides a suitable basis for arithmetic on
/// scalar values, such as integers and floating-point numbers. You can write
/// generic methods that operate on any numeric type in the standard library
/// by using the `Numeric` protocol as a generic constraint.
///
/// The following example extends `Sequence` with a method that returns an
/// array with the sequence's values multiplied by two.
///
/// extension Sequence where Element: Numeric {
/// func doublingAll() -> [Element] {
/// return map { $0 * 2 }
/// }
/// }
///
/// With this extension, any sequence with elements that conform to `Numeric`
/// has the `doublingAll()` method. For example, you can double the elements of
/// an array of doubles or a range of integers:
///
/// let observations = [1.5, 2.0, 3.25, 4.875, 5.5]
/// let doubledObservations = observations.doublingAll()
/// // doubledObservations == [3.0, 4.0, 6.5, 9.75, 11.0]
///
/// let integers = 0..<8
/// let doubledIntegers = integers.doublingAll()
/// // doubledIntegers == [0, 2, 4, 6, 8, 10, 12, 14]
///
/// Conforming to the Numeric Protocol
/// ==================================
///
/// To add `Numeric` protocol conformance to your own custom type, implement
/// the required initializer and operators, and provide a `magnitude` property
/// using a type that can represent the magnitude of any value of your custom
/// type.
public protocol Numeric: AdditiveArithmetic, ExpressibleByIntegerLiteral {
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type.
init?<T: BinaryInteger>(exactly source: T)
/// A type that can represent the absolute value of any possible value of the
/// conforming type.
associatedtype Magnitude: Comparable, Numeric
/// The magnitude of this value.
///
/// For any numeric value `x`, `x.magnitude` is the absolute value of `x`.
/// You can use the `magnitude` property in operations that are simpler to
/// implement in terms of unsigned values, such as printing the value of an
/// integer, which is just printing a '-' character in front of an absolute
/// value.
///
/// let x = -200
/// // x.magnitude == 200
///
/// The global `abs(_:)` function provides more familiar syntax when you need
/// to find an absolute value. In addition, because `abs(_:)` always returns
/// a value of the same type, even in a generic context, using the function
/// instead of the `magnitude` property is encouraged.
var magnitude: Magnitude { get }
/// Multiplies two values and produces their product.
///
/// The multiplication operator (`*`) calculates the product of its two
/// arguments. For example:
///
/// 2 * 3 // 6
/// 100 * 21 // 2100
/// -10 * 15 // -150
/// 3.5 * 2.25 // 7.875
///
/// You cannot use `*` with arguments of different types. To multiply values
/// of different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) * y // 21000000
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
static func *(lhs: Self, rhs: Self) -> Self
/// Multiplies two values and stores the result in the left-hand-side
/// variable.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
static func *=(lhs: inout Self, rhs: Self)
}
/// A type that can represent both positive and negative values.
///
/// The `SignedNumeric` protocol extends the operations defined by the
/// `Numeric` protocol to include a value's additive inverse.
///
/// Conforming to the SignedNumeric Protocol
/// ========================================
///
/// Because the `SignedNumeric` protocol provides default implementations of
/// both of its required methods, you don't need to do anything beyond
/// declaring conformance to the protocol and ensuring that the values of your
/// type support negation. To customize your type's implementation, provide
/// your own mutating `negate()` method.
///
/// When the additive inverse of a value is unrepresentable in a conforming
/// type, the operation should either trap or return an exceptional value. For
/// example, using the negation operator (prefix `-`) with `Int.min` results in
/// a runtime error.
///
/// let x = Int.min
/// let y = -x
/// // Overflow error
public protocol SignedNumeric: Numeric {
/// Returns the additive inverse of the specified value.
///
/// The negation operator (prefix `-`) returns the additive inverse of its
/// argument.
///
/// let x = 21
/// let y = -x
/// // y == -21
///
/// The resulting value must be representable in the same type as the
/// argument. In particular, negating a signed, fixed-width integer type's
/// minimum results in a value that cannot be represented.
///
/// let z = -Int8.min
/// // Overflow error
///
/// - Returns: The additive inverse of this value.
static prefix func - (_ operand: Self) -> Self
/// Replaces this value with its additive inverse.
///
/// The following example uses the `negate()` method to negate the value of
/// an integer `x`:
///
/// var x = 21
/// x.negate()
/// // x == -21
///
/// The resulting value must be representable within the value's type. In
/// particular, negating a signed, fixed-width integer type's minimum
/// results in a value that cannot be represented.
///
/// var y = Int8.min
/// y.negate()
/// // Overflow error
mutating func negate()
}
extension SignedNumeric {
/// Returns the additive inverse of the specified value.
///
/// The negation operator (prefix `-`) returns the additive inverse of its
/// argument.
///
/// let x = 21
/// let y = -x
/// // y == -21
///
/// The resulting value must be representable in the same type as the
/// argument. In particular, negating a signed, fixed-width integer type's
/// minimum results in a value that cannot be represented.
///
/// let z = -Int8.min
/// // Overflow error
///
/// - Returns: The additive inverse of the argument.
@_transparent
public static prefix func - (_ operand: Self) -> Self {
var result = operand
result.negate()
return result
}
/// Replaces this value with its additive inverse.
///
/// The following example uses the `negate()` method to negate the value of
/// an integer `x`:
///
/// var x = 21
/// x.negate()
/// // x == -21
///
/// The resulting value must be representable within the value's type. In
/// particular, negating a signed, fixed-width integer type's minimum
/// results in a value that cannot be represented.
///
/// var y = Int8.min
/// y.negate()
/// // Overflow error
@_transparent
public mutating func negate() {
self = 0 - self
}
}
/// Returns the absolute value of the given number.
///
/// The absolute value of `x` must be representable in the same type. In
/// particular, the absolute value of a signed, fixed-width integer type's
/// minimum cannot be represented.
///
/// let x = Int8.min
/// // x == -128
/// let y = abs(x)
/// // Overflow error
///
/// - Parameter x: A signed number.
/// - Returns: The absolute value of `x`.
@inlinable
public func abs<T: SignedNumeric & Comparable>(_ x: T) -> T {
if T.self == T.Magnitude.self {
return unsafeBitCast(x.magnitude, to: T.self)
}
return x < (0 as T) ? -x : x
}
extension AdditiveArithmetic {
/// Returns the given number unchanged.
///
/// You can use the unary plus operator (`+`) to provide symmetry in your
/// code for positive numbers when also using the unary minus operator.
///
/// let x = -21
/// let y = +21
/// // x == -21
/// // y == 21
///
/// - Returns: The given argument without any changes.
@_transparent
public static prefix func + (x: Self) -> Self {
return x
}
}
//===----------------------------------------------------------------------===//
//===--- BinaryInteger ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type with a binary representation.
///
/// The `BinaryInteger` protocol is the basis for all the integer types
/// provided by the standard library. All of the standard library's integer
/// types, such as `Int` and `UInt32`, conform to `BinaryInteger`.
///
/// Converting Between Numeric Types
/// ================================
///
/// You can create new instances of a type that conforms to the `BinaryInteger`
/// protocol from a floating-point number or another binary integer of any
/// type. The `BinaryInteger` protocol provides initializers for four
/// different kinds of conversion.
///
/// Range-Checked Conversion
/// ------------------------
///
/// You use the default `init(_:)` initializer to create a new instance when
/// you're sure that the value passed is representable in the new type. For
/// example, an instance of `Int16` can represent the value `500`, so the
/// first conversion in the code sample below succeeds. That same value is too
/// large to represent as an `Int8` instance, so the second conversion fails,
/// triggering a runtime error.
///
/// let x: Int = 500
/// let y = Int16(x)
/// // y == 500
///
/// let z = Int8(x)
/// // Error: Not enough bits to represent...
///
/// When you create a binary integer from a floating-point value using the
/// default initializer, the value is rounded toward zero before the range is
/// checked. In the following example, the value `127.75` is rounded to `127`,
/// which is representable by the `Int8` type. `128.25` is rounded to `128`,
/// which is not representable as an `Int8` instance, triggering a runtime
/// error.
///
/// let e = Int8(127.75)
/// // e == 127
///
/// let f = Int8(128.25)
/// // Error: Double value cannot be converted...
///
///
/// Exact Conversion
/// ----------------
///
/// Use the `init?(exactly:)` initializer to create a new instance after
/// checking whether the passed value is representable. Instead of trapping on
/// out-of-range values, using the failable `init?(exactly:)`
/// initializer results in `nil`.
///
/// let x = Int16(exactly: 500)
/// // x == Optional(500)
///
/// let y = Int8(exactly: 500)
/// // y == nil
///
/// When converting floating-point values, the `init?(exactly:)` initializer
/// checks both that the passed value has no fractional part and that the
/// value is representable in the resulting type.
///
/// let e = Int8(exactly: 23.0) // integral value, representable
/// // e == Optional(23)
///
/// let f = Int8(exactly: 23.75) // fractional value, representable
/// // f == nil
///
/// let g = Int8(exactly: 500.0) // integral value, nonrepresentable
/// // g == nil
///
/// Clamping Conversion
/// -------------------
///
/// Use the `init(clamping:)` initializer to create a new instance of a binary
/// integer type where out-of-range values are clamped to the representable
/// range of the type. For a type `T`, the resulting value is in the range
/// `T.min...T.max`.
///
/// let x = Int16(clamping: 500)
/// // x == 500
///
/// let y = Int8(clamping: 500)
/// // y == 127
///
/// let z = UInt8(clamping: -500)
/// // z == 0
///
/// Bit Pattern Conversion
/// ----------------------
///
/// Use the `init(truncatingIfNeeded:)` initializer to create a new instance
/// with the same bit pattern as the passed value, extending or truncating the
/// value's representation as necessary. Note that the value may not be
/// preserved, particularly when converting between signed to unsigned integer
/// types or when the destination type has a smaller bit width than the source
/// type. The following example shows how extending and truncating work for
/// nonnegative integers:
///
/// let q: Int16 = 850
/// // q == 0b00000011_01010010
///
/// let r = Int8(truncatingIfNeeded: q) // truncate 'q' to fit in 8 bits
/// // r == 82
/// // == 0b01010010
///
/// let s = Int16(truncatingIfNeeded: r) // extend 'r' to fill 16 bits
/// // s == 82
/// // == 0b00000000_01010010
///
/// Any padding is performed by *sign-extending* the passed value. When
/// nonnegative integers are extended, the result is padded with zeroes. When
/// negative integers are extended, the result is padded with ones. This
/// example shows several extending conversions of a negative value---note
/// that negative values are sign-extended even when converting to an unsigned
/// type.
///
/// let t: Int8 = -100
/// // t == -100
/// // t's binary representation == 0b10011100
///
/// let u = UInt8(truncatingIfNeeded: t)
/// // u == 156
/// // u's binary representation == 0b10011100
///
/// let v = Int16(truncatingIfNeeded: t)
/// // v == -100
/// // v's binary representation == 0b11111111_10011100
///
/// let w = UInt16(truncatingIfNeeded: t)
/// // w == 65436
/// // w's binary representation == 0b11111111_10011100
///
///
/// Comparing Across Integer Types
/// ==============================
///
/// You can use relational operators, such as the less-than and equal-to
/// operators (`<` and `==`), to compare instances of different binary integer
/// types. The following example compares instances of the `Int`, `UInt`, and
/// `UInt8` types:
///
/// let x: Int = -23
/// let y: UInt = 1_000
/// let z: UInt8 = 23
///
/// if x < y {
/// print("\(x) is less than \(y).")
/// }
/// // Prints "-23 is less than 1000."
///
/// if z > x {
/// print("\(z) is greater than \(x).")
/// }
/// // Prints "23 is greater than -23."
public protocol BinaryInteger :
Hashable, Numeric, CustomStringConvertible, Strideable
where Magnitude: BinaryInteger, Magnitude.Magnitude == Magnitude
{
/// A Boolean value indicating whether this type is a signed integer type.
///
/// *Signed* integer types can represent both positive and negative values.
/// *Unsigned* integer types can represent only nonnegative values.
static var isSigned: Bool { get }
/// Creates an integer from the given floating-point value, if it can be
/// represented exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `21.0`, while the attempt to initialize the
/// constant `y` from `21.5` fails:
///
/// let x = Int(exactly: 21.0)
/// // x == Optional(21)
/// let y = Int(exactly: 21.5)
/// // y == nil
///
/// - Parameter source: A floating-point value to convert to an integer.
init?<T: BinaryFloatingPoint>(exactly source: T)
/// Creates an integer from the given floating-point value, rounding toward
/// zero.
///
/// Any fractional part of the value passed as `source` is removed, rounding
/// the value toward zero.
///
/// let x = Int(21.5)
/// // x == 21
/// let y = Int(-21.5)
/// // y == -21
///
/// If `source` is outside the bounds of this type after rounding toward
/// zero, a runtime error may occur.
///
/// let z = UInt(-21.5)
/// // Error: ...the result would be less than UInt.min
///
/// - Parameter source: A floating-point value to convert to an integer.
/// `source` must be representable in this type after rounding toward
/// zero.
init<T: BinaryFloatingPoint>(_ source: T)
/// Creates a new instance from the given integer.
///
/// If the value passed as `source` is not representable in this type, a
/// runtime error may occur.
///
/// let x = -500 as Int
/// let y = Int32(x)
/// // y == -500
///
/// // -500 is not representable as a 'UInt32' instance
/// let z = UInt32(x)
/// // Error
///
/// - Parameter source: An integer to convert. `source` must be representable
/// in this type.
init<T: BinaryInteger>(_ source: T)
/// Creates a new instance from the bit pattern of the given instance by
/// sign-extending or truncating to fit this type.
///
/// When the bit width of `T` (the type of `source`) is equal to or greater
/// than this type's bit width, the result is the truncated
/// least-significant bits of `source`. For example, when converting a
/// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are
/// used.
///
/// let p: Int16 = -500
/// // 'p' has a binary representation of 11111110_00001100
/// let q = Int8(truncatingIfNeeded: p)
/// // q == 12
/// // 'q' has a binary representation of 00001100
///
/// When the bit width of `T` is less than this type's bit width, the result
/// is *sign-extended* to fill the remaining bits. That is, if `source` is
/// negative, the result is padded with ones; otherwise, the result is
/// padded with zeros.
///
/// let u: Int8 = 21
/// // 'u' has a binary representation of 00010101
/// let v = Int16(truncatingIfNeeded: u)
/// // v == 21
/// // 'v' has a binary representation of 00000000_00010101
///
/// let w: Int8 = -21
/// // 'w' has a binary representation of 11101011
/// let x = Int16(truncatingIfNeeded: w)
/// // x == -21
/// // 'x' has a binary representation of 11111111_11101011
/// let y = UInt16(truncatingIfNeeded: w)
/// // y == 65515
/// // 'y' has a binary representation of 11111111_11101011
///
/// - Parameter source: An integer to convert to this type.
init<T: BinaryInteger>(truncatingIfNeeded source: T)
/// Creates a new instance with the representable value that's closest to the
/// given integer.
///
/// If the value passed as `source` is greater than the maximum representable
/// value in this type, the result is the type's `max` value. If `source` is
/// less than the smallest representable value in this type, the result is
/// the type's `min` value.
///
/// In this example, `x` is initialized as an `Int8` instance by clamping
/// `500` to the range `-128...127`, and `y` is initialized as a `UInt`
/// instance by clamping `-500` to the range `0...UInt.max`.
///
/// let x = Int8(clamping: 500)
/// // x == 127
/// // x == Int8.max
///
/// let y = UInt(clamping: -500)
/// // y == 0
///
/// - Parameter source: An integer to convert to this type.
init<T: BinaryInteger>(clamping source: T)
/// A type that represents the words of a binary integer.
///
/// The `Words` type must conform to the `RandomAccessCollection` protocol
/// with an `Element` type of `UInt` and `Index` type of `Int`.
associatedtype Words: RandomAccessCollection
where Words.Element == UInt, Words.Index == Int
/// A collection containing the words of this value's binary
/// representation, in order from the least significant to most significant.
///
/// Negative values are returned in two's complement representation,
/// regardless of the type's underlying implementation.
var words: Words { get }
/// The least significant word in this value's binary representation.
var _lowWord: UInt { get }
/// The number of bits in the current binary representation of this value.
///
/// This property is a constant for instances of fixed-width integer
/// types.
var bitWidth: Int { get }
/// Returns the integer binary logarithm of this value.
///
/// If the value is negative or zero, a runtime error will occur.
func _binaryLogarithm() -> Int
/// The number of trailing zeros in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number -8 has three trailing zeros.
///
/// let x = Int8(bitPattern: 0b1111_1000)
/// // x == -8
/// // x.trailingZeroBitCount == 3
///
/// If the value is zero, then `trailingZeroBitCount` is equal to `bitWidth`.
var trailingZeroBitCount: Int { get }
/// Returns the quotient of dividing the first value by the second.
///
/// For integer types, any remainder of the division is discarded.
///
/// let x = 21 / 5
/// // x == 4
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func /(lhs: Self, rhs: Self) -> Self
/// Divides the first value by the second and stores the quotient in the
/// left-hand-side variable.
///
/// For integer types, any remainder of the division is discarded.
///
/// var x = 21
/// x /= 5
/// // x == 4
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func /=(lhs: inout Self, rhs: Self)
/// Returns the remainder of dividing the first value by the second.
///
/// The result of the remainder operator (`%`) has the same sign as `lhs` and
/// has a magnitude less than `rhs.magnitude`.
///
/// let x = 22 % 5
/// // x == 2
/// let y = 22 % -5
/// // y == 2
/// let z = -22 % -5
/// // z == -2
///
/// For any two integers `a` and `b`, their quotient `q`, and their remainder
/// `r`, `a == b * q + r`.
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func %(lhs: Self, rhs: Self) -> Self
/// Divides the first value by the second and stores the remainder in the
/// left-hand-side variable.
///
/// The result has the same sign as `lhs` and has a magnitude less than
/// `rhs.magnitude`.
///
/// var x = 22
/// x %= 5
/// // x == 2
///
/// var y = 22
/// y %= -5
/// // y == 2
///
/// var z = -22
/// z %= -5
/// // z == -2
///
/// - Parameters:
/// - lhs: The value to divide.
/// - rhs: The value to divide `lhs` by. `rhs` must not be zero.
static func %=(lhs: inout Self, rhs: Self)
/// Adds two values and produces their sum.
///
/// The addition operator (`+`) calculates the sum of its two arguments. For
/// example:
///
/// 1 + 2 // 3
/// -10 + 15 // 5
/// -15 + -5 // -20
/// 21.5 + 3.25 // 24.75
///
/// You cannot use `+` with arguments of different types. To add values of
/// different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) + y // 1000021
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
override static func +(lhs: Self, rhs: Self) -> Self
/// Adds two values and stores the result in the left-hand-side variable.
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
override static func +=(lhs: inout Self, rhs: Self)
/// Subtracts one value from another and produces their difference.
///
/// The subtraction operator (`-`) calculates the difference of its two
/// arguments. For example:
///
/// 8 - 3 // 5
/// -10 - 5 // -15
/// 100 - -5 // 105
/// 10.5 - 100.0 // -89.5
///
/// You cannot use `-` with arguments of different types. To subtract values
/// of different types, convert one of the values to the other value's type.
///
/// let x: UInt8 = 21
/// let y: UInt = 1000000
/// y - UInt(x) // 999979
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
override static func -(lhs: Self, rhs: Self) -> Self
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable.
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
override static func -=(lhs: inout Self, rhs: Self)
/// Multiplies two values and produces their product.
///
/// The multiplication operator (`*`) calculates the product of its two
/// arguments. For example:
///
/// 2 * 3 // 6
/// 100 * 21 // 2100
/// -10 * 15 // -150
/// 3.5 * 2.25 // 7.875
///
/// You cannot use `*` with arguments of different types. To multiply values
/// of different types, convert one of the values to the other value's type.
///
/// let x: Int8 = 21
/// let y: Int = 1000000
/// Int(x) * y // 21000000
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
override static func *(lhs: Self, rhs: Self) -> Self
/// Multiplies two values and stores the result in the left-hand-side
/// variable.
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
override static func *=(lhs: inout Self, rhs: Self)
/// Returns the inverse of the bits set in the argument.
///
/// The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// in which all the bits of its argument are flipped: Bits that are `1` in
/// the argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on 0 returns a value with every bit
/// set to `1`.
///
/// let allOnes = ~UInt8.min // 0b11111111
///
/// - Complexity: O(1).
static prefix func ~ (_ x: Self) -> Self
/// Returns the result of performing a bitwise AND operation on the two given
/// values.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
/// // z == 4
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func &(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise AND operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x &= y // 0b00000100
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func &=(lhs: inout Self, rhs: Self)
/// Returns the result of performing a bitwise OR operation on the two given
/// values.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
/// // z == 15
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func |(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise OR operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x |= y // 0b00001111
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func |=(lhs: inout Self, rhs: Self)
/// Returns the result of performing a bitwise XOR operation on the two given
/// values.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
/// // z == 11
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func ^(lhs: Self, rhs: Self) -> Self
/// Stores the result of performing a bitwise XOR operation on the two given
/// values in the left-hand-side variable.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// var x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// x ^= y // 0b00001011
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
static func ^=(lhs: inout Self, rhs: Self)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
static func >> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self
/// Stores the result of shifting a value's binary representation the
/// specified number of digits to the right in the left-hand-side variable.
///
/// The `>>=` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// var x: UInt8 = 30 // 0b00011110
/// x >>= 2
/// // x == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// var y: UInt8 = 30 // 0b00011110
/// y >>= 11
/// // y == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// var a: UInt8 = 30 // 0b00011110
/// a >>= -3
/// // a == 240 // 0b11110000
///
/// var b: UInt8 = 30 // 0b00011110
/// b <<= 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// var q: Int8 = -30 // 0b11100010
/// q >>= 2
/// // q == -8 // 0b11111000
///
/// var r: Int8 = -30 // 0b11100010
/// r >>= 11
/// // r == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
static func >>= <RHS: BinaryInteger>(lhs: inout Self, rhs: RHS)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
static func << <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self
/// Stores the result of shifting a value's binary representation the
/// specified number of digits to the left in the left-hand-side variable.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// var x: UInt8 = 30 // 0b00011110
/// x <<= 2
/// // x == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// var y: UInt8 = 30 // 0b00011110
/// y <<= 11
/// // y == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// var a: UInt8 = 30 // 0b00011110
/// a <<= -3
/// // a == 3 // 0b00000011
///
/// var b: UInt8 = 30 // 0b00011110
/// b >>= 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
static func <<=<RHS: BinaryInteger>(lhs: inout Self, rhs: RHS)
/// Returns the quotient and remainder of this value divided by the given
/// value.
///
/// Use this method to calculate the quotient and remainder of a division at
/// the same time.
///
/// let x = 1_000_000
/// let (q, r) = x.quotientAndRemainder(dividingBy: 933)
/// // q == 1071
/// // r == 757
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the quotient and remainder of this value
/// divided by `rhs`. The remainder has the same sign as `lhs`.
func quotientAndRemainder(dividingBy rhs: Self)
-> (quotient: Self, remainder: Self)
/// Returns `true` if this value is a multiple of the given value, and `false`
/// otherwise.
///
/// For two integers *a* and *b*, *a* is a multiple of *b* if there exists a
/// third integer *q* such that _a = q*b_. For example, *6* is a multiple of
/// *3* because _6 = 2*3_. Zero is a multiple of everything because _0 = 0*x_
/// for any integer *x*.
///
/// Two edge cases are worth particular attention:
/// - `x.isMultiple(of: 0)` is `true` if `x` is zero and `false` otherwise.
/// - `T.min.isMultiple(of: -1)` is `true` for signed integer `T`, even
/// though the quotient `T.min / -1` isn't representable in type `T`.
///
/// - Parameter other: The value to test.
func isMultiple(of other: Self) -> Bool
/// Returns `-1` if this value is negative and `1` if it's positive;
/// otherwise, `0`.
///
/// - Returns: The sign of this number, expressed as an integer of the same
/// type.
func signum() -> Self
}
extension BinaryInteger {
/// Creates a new value equal to zero.
@_transparent
public init() {
self = 0
}
/// Returns `-1` if this value is negative and `1` if it's positive;
/// otherwise, `0`.
///
/// - Returns: The sign of this number, expressed as an integer of the same
/// type.
@inlinable
public func signum() -> Self {
return (self > (0 as Self) ? 1 : 0) - (self < (0 as Self) ? 1 : 0)
}
@_transparent
public var _lowWord: UInt {
var it = words.makeIterator()
return it.next() ?? 0
}
@inlinable
public func _binaryLogarithm() -> Int {
_precondition(self > (0 as Self))
var (quotient, remainder) =
(bitWidth &- 1).quotientAndRemainder(dividingBy: UInt.bitWidth)
remainder = remainder &+ 1
var word = UInt(truncatingIfNeeded: self >> (bitWidth &- remainder))
// If, internally, a variable-width binary integer uses digits of greater
// bit width than that of Magnitude.Words.Element (i.e., UInt), then it is
// possible that `word` could be zero. Additionally, a signed variable-width
// binary integer may have a leading word that is zero to store a clear sign
// bit.
while word == 0 {
quotient = quotient &- 1
remainder = remainder &+ UInt.bitWidth
word = UInt(truncatingIfNeeded: self >> (bitWidth &- remainder))
}
// Note that the order of operations below is important to guarantee that
// we won't overflow.
return UInt.bitWidth &* quotient &+
(UInt.bitWidth &- (word.leadingZeroBitCount &+ 1))
}
/// Returns the quotient and remainder of this value divided by the given
/// value.
///
/// Use this method to calculate the quotient and remainder of a division at
/// the same time.
///
/// let x = 1_000_000
/// let (q, r) = x.quotientAndRemainder(dividingBy: 933)
/// // q == 1071
/// // r == 757
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the quotient and remainder of this value
/// divided by `rhs`.
@inlinable
public func quotientAndRemainder(dividingBy rhs: Self)
-> (quotient: Self, remainder: Self) {
return (self / rhs, self % rhs)
}
@inlinable
public func isMultiple(of other: Self) -> Bool {
// Nothing but zero is a multiple of zero.
if other == 0 { return self == 0 }
// Do the test in terms of magnitude, which guarantees there are no other
// edge cases. If we write this as `self % other` instead, it could trap
// for types that are not symmetric around zero.
return self.magnitude % other.magnitude == 0
}
//===----------------------------------------------------------------------===//
//===--- Homogeneous ------------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Returns the result of performing a bitwise AND operation on the two given
/// values.
///
/// A bitwise AND operation results in a value that has each bit set to `1`
/// where *both* of its arguments have that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x & y // 0b00000100
/// // z == 4
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func & (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &= rhs
return lhs
}
/// Returns the result of performing a bitwise OR operation on the two given
/// values.
///
/// A bitwise OR operation results in a value that has each bit set to `1`
/// where *one or both* of its arguments have that bit set to `1`. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x | y // 0b00001111
/// // z == 15
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func | (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs |= rhs
return lhs
}
/// Returns the result of performing a bitwise XOR operation on the two given
/// values.
///
/// A bitwise XOR operation, also known as an exclusive OR operation, results
/// in a value that has each bit set to `1` where *one or the other but not
/// both* of its arguments had that bit set to `1`. For example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let y: UInt8 = 14 // 0b00001110
/// let z = x ^ y // 0b00001011
/// // z == 11
///
/// - Parameters:
/// - lhs: An integer value.
/// - rhs: Another integer value.
@_transparent
public static func ^ (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs ^= rhs
return lhs
}
//===----------------------------------------------------------------------===//
//===--- Heterogeneous non-masking shift in terms of shift-assignment -----===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func >> <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self {
var r = lhs
r >>= rhs
return r
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func << <RHS: BinaryInteger>(lhs: Self, rhs: RHS) -> Self {
var r = lhs
r <<= rhs
return r
}
}
//===----------------------------------------------------------------------===//
//===--- CustomStringConvertible conformance ------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
internal func _description(radix: Int, uppercase: Bool) -> String {
_precondition(2...36 ~= radix, "Radix must be between 2 and 36")
if bitWidth <= 64 {
let radix_ = Int64(radix)
return Self.isSigned
? _int64ToString(
Int64(truncatingIfNeeded: self), radix: radix_, uppercase: uppercase)
: _uint64ToString(
UInt64(truncatingIfNeeded: self), radix: radix_, uppercase: uppercase)
}
if self == (0 as Self) { return "0" }
// Bit shifting can be faster than division when `radix` is a power of two
// (although not necessarily the case for builtin types).
let isRadixPowerOfTwo = radix.nonzeroBitCount == 1
let radix_ = Magnitude(radix)
func _quotientAndRemainder(_ value: Magnitude) -> (Magnitude, Magnitude) {
return isRadixPowerOfTwo
? (value >> radix.trailingZeroBitCount, value & (radix_ - 1))
: value.quotientAndRemainder(dividingBy: radix_)
}
let hasLetters = radix > 10
func _ascii(_ digit: UInt8) -> UInt8 {
let base: UInt8
if !hasLetters || digit < 10 {
base = UInt8(("0" as Unicode.Scalar).value)
} else if uppercase {
base = UInt8(("A" as Unicode.Scalar).value) &- 10
} else {
base = UInt8(("a" as Unicode.Scalar).value) &- 10
}
return base &+ digit
}
let isNegative = Self.isSigned && self < (0 as Self)
var value = magnitude
// TODO(FIXME JIRA): All current stdlib types fit in small. Use a stack
// buffer instead of an array on the heap.
var result: [UInt8] = []
while value != 0 {
let (quotient, remainder) = _quotientAndRemainder(value)
result.append(_ascii(UInt8(truncatingIfNeeded: remainder)))
value = quotient
}
if isNegative {
result.append(UInt8(("-" as Unicode.Scalar).value))
}
result.reverse()
return result.withUnsafeBufferPointer {
return String._fromASCII($0)
}
}
/// A textual representation of this value.
@_semantics("binaryInteger.description")
public var description: String {
return _description(radix: 10, uppercase: false)
}
}
//===----------------------------------------------------------------------===//
//===--- Strideable conformance -------------------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
/// Returns the distance from this value to the given value, expressed as a
/// stride.
///
/// For two values `x` and `y`, and a distance `n = x.distance(to: y)`,
/// `x.advanced(by: n) == y`.
///
/// - Parameter other: The value to calculate the distance to.
/// - Returns: The distance from this value to `other`.
@inlinable
@inline(__always)
public func distance(to other: Self) -> Int {
if !Self.isSigned {
if self > other {
if let result = Int(exactly: self - other) {
return -result
}
} else {
if let result = Int(exactly: other - self) {
return result
}
}
} else {
let isNegative = self < (0 as Self)
if isNegative == (other < (0 as Self)) {
if let result = Int(exactly: other - self) {
return result
}
} else {
if let result = Int(exactly: self.magnitude + other.magnitude) {
return isNegative ? result : -result
}
}
}
_preconditionFailure("Distance is not representable in Int")
}
/// Returns a value that is offset the specified distance from this value.
///
/// Use the `advanced(by:)` method in generic code to offset a value by a
/// specified distance. If you're working directly with numeric values, use
/// the addition operator (`+`) instead of this method.
///
/// For a value `x`, a distance `n`, and a value `y = x.advanced(by: n)`,
/// `x.distance(to: y) == n`.
///
/// - Parameter n: The distance to advance this value.
/// - Returns: A value that is offset from this value by `n`.
@inlinable
@inline(__always)
public func advanced(by n: Int) -> Self {
if !Self.isSigned {
return n < (0 as Int)
? self - Self(-n)
: self + Self(n)
}
if (self < (0 as Self)) == (n < (0 as Self)) {
return self + Self(n)
}
return self.magnitude < n.magnitude
? Self(Int(self) + n)
: self + Self(n)
}
}
//===----------------------------------------------------------------------===//
//===--- Heterogeneous comparison -----------------------------------------===//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
/// Returns a Boolean value indicating whether the two given values are
/// equal.
///
/// You can check the equality of instances of any `BinaryInteger` types
/// using the equal-to operator (`==`). For example, you can test whether
/// the first `UInt8` value in a string's UTF-8 encoding is equal to the
/// first `UInt32` value in its Unicode scalar view:
///
/// let gameName = "Red Light, Green Light"
/// if let firstUTF8 = gameName.utf8.first,
/// let firstScalar = gameName.unicodeScalars.first?.value {
/// print("First code values are equal: \(firstUTF8 == firstScalar)")
/// }
/// // Prints "First code values are equal: true"
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func == <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Bool {
let lhsNegative = Self.isSigned && lhs < (0 as Self)
let rhsNegative = Other.isSigned && rhs < (0 as Other)
if lhsNegative != rhsNegative { return false }
// Here we know the values are of the same sign.
//
// There are a few possible scenarios from here:
//
// 1. Both values are negative
// - If one value is strictly wider than the other, then it is safe to
// convert to the wider type.
// - If the values are of the same width, it does not matter which type we
// choose to convert to as the values are already negative, and thus
// include the sign bit if two's complement representation already.
// 2. Both values are non-negative
// - If one value is strictly wider than the other, then it is safe to
// convert to the wider type.
// - If the values are of the same width, than signedness matters, as not
// unsigned types are 'wider' in a sense they don't need to 'waste' the
// sign bit. Therefore it is safe to convert to the unsigned type.
if lhs.bitWidth < rhs.bitWidth {
return Other(truncatingIfNeeded: lhs) == rhs
}
if lhs.bitWidth > rhs.bitWidth {
return lhs == Self(truncatingIfNeeded: rhs)
}
if Self.isSigned {
return Other(truncatingIfNeeded: lhs) == rhs
}
return lhs == Self(truncatingIfNeeded: rhs)
}
/// Returns a Boolean value indicating whether the two given values are not
/// equal.
///
/// You can check the inequality of instances of any `BinaryInteger` types
/// using the not-equal-to operator (`!=`). For example, you can test
/// whether the first `UInt8` value in a string's UTF-8 encoding is not
/// equal to the first `UInt32` value in its Unicode scalar view:
///
/// let gameName = "Red Light, Green Light"
/// if let firstUTF8 = gameName.utf8.first,
/// let firstScalar = gameName.unicodeScalars.first?.value {
/// print("First code values are different: \(firstUTF8 != firstScalar)")
/// }
/// // Prints "First code values are different: false"
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func != <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Bool {
return !(lhs == rhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// less-than operator (`<`), even if the two instances are of different
/// types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func < <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
let lhsNegative = Self.isSigned && lhs < (0 as Self)
let rhsNegative = Other.isSigned && rhs < (0 as Other)
if lhsNegative != rhsNegative { return lhsNegative }
if lhs == (0 as Self) && rhs == (0 as Other) { return false }
// if we get here, lhs and rhs have the same sign. If they're negative,
// then Self and Other are both signed types, and one of them can represent
// values of the other type. Otherwise, lhs and rhs are positive, and one
// of Self, Other may be signed and the other unsigned.
let rhsAsSelf = Self(truncatingIfNeeded: rhs)
let rhsAsSelfNegative = rhsAsSelf < (0 as Self)
// Can we round-trip rhs through Other?
if Other(truncatingIfNeeded: rhsAsSelf) == rhs &&
// This additional check covers the `Int8.max < (128 as UInt8)` case.
// Since the types are of the same width, init(truncatingIfNeeded:)
// will result in a simple bitcast, so that rhsAsSelf would be -128, and
// `lhs < rhsAsSelf` will return false.
// We basically guard against that bitcast by requiring rhs and rhsAsSelf
// to be the same sign.
rhsNegative == rhsAsSelfNegative {
return lhs < rhsAsSelf
}
return Other(truncatingIfNeeded: lhs) < rhs
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is less than or equal to that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// less-than-or-equal-to operator (`<=`), even if the two instances are of
/// different types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func <= <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return !(rhs < lhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than or equal to that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// greater-than-or-equal-to operator (`>=`), even if the two instances are
/// of different types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func >= <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return !(lhs < rhs)
}
/// Returns a Boolean value indicating whether the value of the first
/// argument is greater than that of the second argument.
///
/// You can compare instances of any `BinaryInteger` types using the
/// greater-than operator (`>`), even if the two instances are of different
/// types.
///
/// - Parameters:
/// - lhs: An integer to compare.
/// - rhs: Another integer to compare.
@_transparent
public static func > <Other: BinaryInteger>(lhs: Self, rhs: Other) -> Bool {
return rhs < lhs
}
}
//===----------------------------------------------------------------------===//
//===--- Ambiguity breakers -----------------------------------------------===//
//
// These two versions of the operators are not ordered with respect to one
// another, but the compiler choses the second one, and that results in infinite
// recursion.
//
// <T: Comparable>(T, T) -> Bool
// <T: BinaryInteger, U: BinaryInteger>(T, U) -> Bool
//
// so we define:
//
// <T: BinaryInteger>(T, T) -> Bool
//
//===----------------------------------------------------------------------===//
extension BinaryInteger {
@_transparent
public static func != (lhs: Self, rhs: Self) -> Bool {
return !(lhs == rhs)
}
@_transparent
public static func <= (lhs: Self, rhs: Self) -> Bool {
return !(rhs < lhs)
}
@_transparent
public static func >= (lhs: Self, rhs: Self) -> Bool {
return !(lhs < rhs)
}
@_transparent
public static func > (lhs: Self, rhs: Self) -> Bool {
return rhs < lhs
}
}
//===----------------------------------------------------------------------===//
//===--- FixedWidthInteger ------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that uses a fixed size for every instance.
///
/// The `FixedWidthInteger` protocol adds binary bitwise operations, bit
/// shifts, and overflow handling to the operations supported by the
/// `BinaryInteger` protocol.
///
/// Use the `FixedWidthInteger` protocol as a constraint or extension point
/// when writing operations that depend on bit shifting, performing bitwise
/// operations, catching overflows, or having access to the maximum or minimum
/// representable value of a type. For example, the following code provides a
/// `binaryString` property on every fixed-width integer that represents the
/// number's binary representation, split into 8-bit chunks.
///
/// extension FixedWidthInteger {
/// var binaryString: String {
/// var result: [String] = []
/// for i in 0..<(Self.bitWidth / 8) {
/// let byte = UInt8(truncatingIfNeeded: self >> (i * 8))
/// let byteString = String(byte, radix: 2)
/// let padding = String(repeating: "0",
/// count: 8 - byteString.count)
/// result.append(padding + byteString)
/// }
/// return "0b" + result.reversed().joined(separator: "_")
/// }
/// }
///
/// print(Int16.max.binaryString)
/// // Prints "0b01111111_11111111"
/// print((101 as UInt8).binaryString)
/// // Prints "0b11001001"
///
/// The `binaryString` implementation uses the static `bitWidth` property and
/// the right shift operator (`>>`), both of which are available to any type
/// that conforms to the `FixedWidthInteger` protocol.
///
/// The next example declares a generic `squared` function, which accepts an
/// instance `x` of any fixed-width integer type. The function uses the
/// `multipliedReportingOverflow(by:)` method to multiply `x` by itself and
/// check whether the result is too large to represent in the same type.
///
/// func squared<T: FixedWidthInteger>(_ x: T) -> T? {
/// let (result, overflow) = x.multipliedReportingOverflow(by: x)
/// if overflow {
/// return nil
/// }
/// return result
/// }
///
/// let (x, y): (Int8, Int8) = (9, 123)
/// print(squared(x))
/// // Prints "Optional(81)"
/// print(squared(y))
/// // Prints "nil"
///
/// Conforming to the FixedWidthInteger Protocol
/// ============================================
///
/// To make your own custom type conform to the `FixedWidthInteger` protocol,
/// declare the required initializers, properties, and methods. The required
/// methods that are suffixed with `ReportingOverflow` serve as the
/// customization points for arithmetic operations. When you provide just those
/// methods, the standard library provides default implementations for all
/// other arithmetic methods and operators.
public protocol FixedWidthInteger: BinaryInteger, LosslessStringConvertible
where Magnitude: FixedWidthInteger & UnsignedInteger,
Stride: FixedWidthInteger & SignedInteger {
/// The number of bits used for the underlying binary representation of
/// values of this type.
///
/// An unsigned, fixed-width integer type can represent values from 0 through
/// `(2 ** bitWidth) - 1`, where `**` is exponentiation. A signed,
/// fixed-width integer type can represent values from
/// `-(2 ** (bitWidth - 1))` through `(2 ** (bitWidth - 1)) - 1`. For example,
/// the `Int8` type has a `bitWidth` value of 8 and can store any integer in
/// the range `-128...127`.
static var bitWidth: Int { get }
/// The maximum representable integer in this type.
///
/// For unsigned integer types, this value is `(2 ** bitWidth) - 1`, where
/// `**` is exponentiation. For signed integer types, this value is
/// `(2 ** (bitWidth - 1)) - 1`.
static var max: Self { get }
/// The minimum representable integer in this type.
///
/// For unsigned integer types, this value is always `0`. For signed integer
/// types, this value is `-(2 ** (bitWidth - 1))`, where `**` is
/// exponentiation.
static var min: Self { get }
/// Returns the sum of this value and the given value, along with a Boolean
/// value indicating whether overflow occurred in the operation.
///
/// - Parameter rhs: The value to add to this value.
/// - Returns: A tuple containing the result of the addition along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// sum. If the `overflow` component is `true`, an overflow occurred and
/// the `partialValue` component contains the truncated sum of this value
/// and `rhs`.
func addingReportingOverflow(
_ rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the difference obtained by subtracting the given value from this
/// value, along with a Boolean value indicating whether overflow occurred in
/// the operation.
///
/// - Parameter rhs: The value to subtract from this value.
/// - Returns: A tuple containing the result of the subtraction along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// difference. If the `overflow` component is `true`, an overflow occurred
/// and the `partialValue` component contains the truncated result of `rhs`
/// subtracted from this value.
func subtractingReportingOverflow(
_ rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the product of this value and the given value, along with a
/// Boolean value indicating whether overflow occurred in the operation.
///
/// - Parameter rhs: The value to multiply by this value.
/// - Returns: A tuple containing the result of the multiplication along with
/// a Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// product. If the `overflow` component is `true`, an overflow occurred and
/// the `partialValue` component contains the truncated product of this
/// value and `rhs`.
func multipliedReportingOverflow(
by rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the quotient obtained by dividing this value by the given value,
/// along with a Boolean value indicating whether overflow occurred in the
/// operation.
///
/// Dividing by zero is not an error when using this method. For a value `x`,
/// the result of `x.dividedReportingOverflow(by: 0)` is `(x, true)`.
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the result of the division along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// quotient. If the `overflow` component is `true`, an overflow occurred
/// and the `partialValue` component contains either the truncated quotient
/// or, if the quotient is undefined, the dividend.
func dividedReportingOverflow(
by rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns the remainder after dividing this value by the given value, along
/// with a Boolean value indicating whether overflow occurred during division.
///
/// Dividing by zero is not an error when using this method. For a value `x`,
/// the result of `x.remainderReportingOverflow(dividingBy: 0)` is
/// `(x, true)`.
///
/// - Parameter rhs: The value to divide this value by.
/// - Returns: A tuple containing the result of the operation along with a
/// Boolean value indicating whether overflow occurred. If the `overflow`
/// component is `false`, the `partialValue` component contains the entire
/// remainder. If the `overflow` component is `true`, an overflow occurred
/// during division and the `partialValue` component contains either the
/// entire remainder or, if the remainder is undefined, the dividend.
func remainderReportingOverflow(
dividingBy rhs: Self
) -> (partialValue: Self, overflow: Bool)
/// Returns a tuple containing the high and low parts of the result of
/// multiplying this value by the given value.
///
/// Use this method to calculate the full result of a product that would
/// otherwise overflow. Unlike traditional truncating multiplication, the
/// `multipliedFullWidth(by:)` method returns a tuple containing both the
/// `high` and `low` parts of the product of this value and `other`. The
/// following example uses this method to multiply two `Int8` values that
/// normally overflow when multiplied:
///
/// let x: Int8 = 48
/// let y: Int8 = -40
/// let result = x.multipliedFullWidth(by: y)
/// // result.high == -8
/// // result.low == 128
///
/// The product of `x` and `y` is `-1920`, which is too large to represent in
/// an `Int8` instance. The `high` and `low` compnents of the `result` value
/// represent `-1920` when concatenated to form a double-width integer; that
/// is, using `result.high` as the high byte and `result.low` as the low byte
/// of an `Int16` instance.
///
/// let z = Int16(result.high) << 8 | Int16(result.low)
/// // z == -1920
///
/// - Parameter other: The value to multiply this value by.
/// - Returns: A tuple containing the high and low parts of the result of
/// multiplying this value and `other`.
func multipliedFullWidth(by other: Self) -> (high: Self, low: Self.Magnitude)
/// Returns a tuple containing the quotient and remainder obtained by dividing
/// the given value by this value.
///
/// The resulting quotient must be representable within the bounds of the
/// type. If the quotient is too large to represent in the type, a runtime
/// error may occur.
///
/// The following example divides a value that is too large to be represented
/// using a single `Int` instance by another `Int` value. Because the quotient
/// is representable as an `Int`, the division succeeds.
///
/// // 'dividend' represents the value 0x506f70652053616e74612049494949
/// let dividend = (22640526660490081, 7959093232766896457 as UInt)
/// let divisor = 2241543570477705381
///
/// let (quotient, remainder) = divisor.dividingFullWidth(dividend)
/// // quotient == 186319822866995413
/// // remainder == 0
///
/// - Parameter dividend: A tuple containing the high and low parts of a
/// double-width integer.
/// - Returns: A tuple containing the quotient and remainder obtained by
/// dividing `dividend` by this value.
func dividingFullWidth(_ dividend: (high: Self, low: Self.Magnitude))
-> (quotient: Self, remainder: Self)
init(_truncatingBits bits: UInt)
/// The number of bits equal to 1 in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number *31* has five bits equal to *1*.
///
/// let x: Int8 = 0b0001_1111
/// // x == 31
/// // x.nonzeroBitCount == 5
var nonzeroBitCount: Int { get }
/// The number of leading zeros in this value's binary representation.
///
/// For example, in a fixed-width integer type with a `bitWidth` value of 8,
/// the number *31* has three leading zeros.
///
/// let x: Int8 = 0b0001_1111
/// // x == 31
/// // x.leadingZeroBitCount == 3
///
/// If the value is zero, then `leadingZeroBitCount` is equal to `bitWidth`.
var leadingZeroBitCount: Int { get }
/// Creates an integer from its big-endian representation, changing the byte
/// order if necessary.
///
/// - Parameter value: A value to use as the big-endian representation of the
/// new integer.
init(bigEndian value: Self)
/// Creates an integer from its little-endian representation, changing the
/// byte order if necessary.
///
/// - Parameter value: A value to use as the little-endian representation of
/// the new integer.
init(littleEndian value: Self)
/// The big-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a big-endian platform, for any
/// integer `x`, `x == x.bigEndian`.
var bigEndian: Self { get }
/// The little-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a little-endian platform, for any
/// integer `x`, `x == x.littleEndian`.
var littleEndian: Self { get }
/// A representation of this integer with the byte order swapped.
var byteSwapped: Self { get }
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &>>(lhs: Self, rhs: Self) -> Self
/// Calculates the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&>>=` operator performs a *masking shift*, where the value passed as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &>>= 2
/// // x == 7 // 0b00000111
///
/// However, if you use `19` as `rhs`, the operation first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &>>= 19
/// // y == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &>>=(lhs: inout Self, rhs: Self)
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &<<(lhs: Self, rhs: Self) -> Self
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&<<=` operator performs a *masking shift*, where the value used as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &<<= 2
/// // x == 120 // 0b01111000
///
/// However, if you pass `19` as `rhs`, the method first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &<<= 19
/// // y == 240 // 0b11110000
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
static func &<<=(lhs: inout Self, rhs: Self)
}
extension FixedWidthInteger {
/// The number of bits in the binary representation of this value.
@inlinable
public var bitWidth: Int { return Self.bitWidth }
@inlinable
public func _binaryLogarithm() -> Int {
_precondition(self > (0 as Self))
return Self.bitWidth &- (leadingZeroBitCount &+ 1)
}
/// Creates an integer from its little-endian representation, changing the
/// byte order if necessary.
///
/// - Parameter value: A value to use as the little-endian representation of
/// the new integer.
@inlinable
public init(littleEndian value: Self) {
#if _endian(little)
self = value
#else
self = value.byteSwapped
#endif
}
/// Creates an integer from its big-endian representation, changing the byte
/// order if necessary.
///
/// - Parameter value: A value to use as the big-endian representation of the
/// new integer.
@inlinable
public init(bigEndian value: Self) {
#if _endian(big)
self = value
#else
self = value.byteSwapped
#endif
}
/// The little-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a little-endian platform, for any
/// integer `x`, `x == x.littleEndian`.
@inlinable
public var littleEndian: Self {
#if _endian(little)
return self
#else
return byteSwapped
#endif
}
/// The big-endian representation of this integer.
///
/// If necessary, the byte order of this value is reversed from the typical
/// byte order of this integer type. On a big-endian platform, for any
/// integer `x`, `x == x.bigEndian`.
@inlinable
public var bigEndian: Self {
#if _endian(big)
return self
#else
return byteSwapped
#endif
}
// Default implementation of multipliedFullWidth.
//
// This implementation is mainly intended for [U]Int64 on 32b platforms. It
// will not be especially efficient for other types that do not provide their
// own implementation, but neither will it be catastrophically bad. It can
// surely be improved on even for Int64, but that is mostly an optimization
// problem; the basic algorithm here gives the compiler all the information
// that it needs to generate efficient code.
@_alwaysEmitIntoClient
public func multipliedFullWidth(by other: Self) -> (high: Self, low: Magnitude) {
// We define a utility function for splitting an integer into high and low
// halves. Note that the low part is always unsigned, while the high part
// matches the signedness of the input type. Both result types are the
// full width of the original number; this may be surprising at first, but
// there are two reasons for it:
//
// - we're going to use these as inputs to a multiplication operation, and
// &* is quite a bit less verbose than `multipliedFullWidth`, so it makes
// the rest of the code in this function somewhat easier to read.
//
// - there's no "half width type" that we can get at from this generic
// context, so there's not really another option anyway.
//
// Fortunately, the compiler is pretty good about propagating the necessary
// information to optimize away unnecessary arithmetic.
func split<T: FixedWidthInteger>(_ x: T) -> (high: T, low: T.Magnitude) {
let n = T.bitWidth/2
return (x >> n, T.Magnitude(truncatingIfNeeded: x) & ((1 &<< n) &- 1))
}
// Split `self` and `other` into high and low parts, compute the partial
// products carrying high words in as we go. We use the wrapping operators
// and `truncatingIfNeeded` inits purely as an optimization hint to the
// compiler; none of these operations will ever wrap due to the constraints
// on the arithmetic. The bounds are documented before each line for signed
// types. For unsigned types, the bounds are much more well known and
// easier to derive, so I haven't bothered to document them here, but they
// all boil down to the fact that a*b + c + d cannot overflow a double-
// width result with unsigned a, b, c, d.
let (x1, x0) = split(self)
let (y1, y0) = split(other)
// If B is 2^bitWidth/2, x0 and y0 are in 0 ... B-1, so their product is
// in 0 ... B^2-2B+1. For further analysis, we'll need the fact that
// the high word is in 0 ... B-2.
let p00 = x0 &* y0
// x1 is in -B/2 ... B/2-1, so the product x1*y0 is in
// -(B^2-B)/2 ... (B^2-3B+2)/2; after adding the high word of p00, the
// result is in -(B^2-B)/2 ... (B^2-B-2)/2.
let p01 = x1 &* Self(y0) &+ Self(split(p00).high)
// The previous analysis holds for this product as well, and the sum is
// in -(B^2-B)/2 ... (B^2-B)/2.
let p10 = Self(x0) &* y1 &+ Self(split(p01).low)
// No analysis is necessary for this term, because we know the product as
// a whole cannot overflow, and this term is the final high word of the
// product.
let p11 = x1 &* y1 &+ split(p01).high &+ split(p10).high
// Now we only need to assemble the low word of the product.
return (p11, split(p10).low << (bitWidth/2) | split(p00).low)
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>> (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &>>= rhs
return lhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width.
///
/// Use the masking right shift operator (`&>>`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking right shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &>> 2
/// // y == 7 // 0b00000111
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &>> 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>> <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
return lhs &>> Self(truncatingIfNeeded: rhs)
}
/// Calculates the result of shifting a value's binary representation the
/// specified number of digits to the right, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&>>=` operator performs a *masking shift*, where the value passed as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &>>= 2
/// // x == 7 // 0b00000111
///
/// However, if you use `19` as `rhs`, the operation first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &>>= 19
/// // y == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &>>= <
Other: BinaryInteger
>(lhs: inout Self, rhs: Other) {
lhs = lhs &>> rhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<< (lhs: Self, rhs: Self) -> Self {
var lhs = lhs
lhs &<<= rhs
return lhs
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width.
///
/// Use the masking left shift operator (`&<<`) when you need to perform a
/// shift and are sure that the shift amount is in the range
/// `0..<lhs.bitWidth`. Before shifting, the masking left shift operator
/// masks the shift to this range. The shift is performed using this masked
/// value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x &<< 2
/// // y == 120 // 0b01111000
///
/// However, if you use `8` as the shift amount, the method first masks the
/// shift amount to zero, and then performs the shift, resulting in no change
/// to the original value.
///
/// let z = x &<< 8
/// // z == 30 // 0b00011110
///
/// If the bit width of the shifted integer type is a power of two, masking
/// is performed using a bitmask; otherwise, masking is performed using a
/// modulo operation.
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<< <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
return lhs &<< Self(truncatingIfNeeded: rhs)
}
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left, masking the shift amount to the
/// type's bit width, and stores the result in the left-hand-side variable.
///
/// The `&<<=` operator performs a *masking shift*, where the value used as
/// `rhs` is masked to produce a value in the range `0..<lhs.bitWidth`. The
/// shift is performed using this masked value.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the shift amount requires no masking.
///
/// var x: UInt8 = 30 // 0b00011110
/// x &<<= 2
/// // x == 120 // 0b01111000
///
/// However, if you pass `19` as `rhs`, the method first bitmasks `rhs` to
/// `3`, and then uses that masked value as the number of bits to shift `lhs`.
///
/// var y: UInt8 = 30 // 0b00011110
/// y &<<= 19
/// // y == 240 // 0b11110000
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left. If `rhs` is
/// outside the range `0..<lhs.bitWidth`, it is masked to produce a
/// value within that range.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func &<<= <
Other: BinaryInteger
>(lhs: inout Self, rhs: Other) {
lhs = lhs &<< rhs
}
}
extension FixedWidthInteger {
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate an integer within a specific range when you
/// are using a custom random number generator. This example creates three
/// new values in the range `1..<100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1..<100, using: &myGenerator))
/// }
/// // Prints "7"
/// // Prints "44"
/// // Prints "21"
///
/// - Note: The algorithm used to create random values may change in a future
/// version of Swift. If you're passing a generator that results in the
/// same sequence of integer values each time you run your program, that
/// sequence may change when your program is compiled using a different
/// version of Swift.
///
/// - Parameters:
/// - range: The range in which to create a random value.
/// `range` must not be empty.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: Range<Self>,
using generator: inout T
) -> Self {
_precondition(
!range.isEmpty,
"Can't get random value with an empty range"
)
// Compute delta, the distance between the lower and upper bounds. This
// value may not representable by the type Bound if Bound is signed, but
// is always representable as Bound.Magnitude.
let delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound)
// The mathematical result we want is lowerBound plus a random value in
// 0 ..< delta. We need to be slightly careful about how we do this
// arithmetic; the Bound type cannot generally represent the random value,
// so we use a wrapping addition on Bound.Magnitude. This will often
// overflow, but produces the correct bit pattern for the result when
// converted back to Bound.
return Self(truncatingIfNeeded:
Magnitude(truncatingIfNeeded: range.lowerBound) &+
generator.next(upperBound: delta)
)
}
/// Returns a random value within the specified range.
///
/// Use this method to generate an integer within a specific range. This
/// example creates three new values in the range `1..<100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1..<100))
/// }
/// // Prints "53"
/// // Prints "64"
/// // Prints "5"
///
/// This method is equivalent to calling the version that takes a generator,
/// passing in the system's default random generator.
///
/// - Parameter range: The range in which to create a random value.
/// `range` must not be empty.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: Range<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
/// Returns a random value within the specified range, using the given
/// generator as a source for randomness.
///
/// Use this method to generate an integer within a specific range when you
/// are using a custom random number generator. This example creates three
/// new values in the range `1...100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1...100, using: &myGenerator))
/// }
/// // Prints "7"
/// // Prints "44"
/// // Prints "21"
///
/// - Parameters:
/// - range: The range in which to create a random value.
/// - generator: The random number generator to use when creating the
/// new random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random<T: RandomNumberGenerator>(
in range: ClosedRange<Self>,
using generator: inout T
) -> Self {
// Compute delta, the distance between the lower and upper bounds. This
// value may not representable by the type Bound if Bound is signed, but
// is always representable as Bound.Magnitude.
var delta = Magnitude(truncatingIfNeeded: range.upperBound &- range.lowerBound)
// Subtle edge case: if the range is the whole set of representable values,
// then adding one to delta to account for a closed range will overflow.
// If we used &+ instead, the result would be zero, which isn't helpful,
// so we actually need to handle this case separately.
if delta == Magnitude.max {
return Self(truncatingIfNeeded: generator.next() as Magnitude)
}
// Need to widen delta to account for the right-endpoint of a closed range.
delta += 1
// The mathematical result we want is lowerBound plus a random value in
// 0 ..< delta. We need to be slightly careful about how we do this
// arithmetic; the Bound type cannot generally represent the random value,
// so we use a wrapping addition on Bound.Magnitude. This will often
// overflow, but produces the correct bit pattern for the result when
// converted back to Bound.
return Self(truncatingIfNeeded:
Magnitude(truncatingIfNeeded: range.lowerBound) &+
generator.next(upperBound: delta)
)
}
/// Returns a random value within the specified range.
///
/// Use this method to generate an integer within a specific range. This
/// example creates three new values in the range `1...100`.
///
/// for _ in 1...3 {
/// print(Int.random(in: 1...100))
/// }
/// // Prints "53"
/// // Prints "64"
/// // Prints "5"
///
/// This method is equivalent to calling `random(in:using:)`, passing in the
/// system's default random generator.
///
/// - Parameter range: The range in which to create a random value.
/// - Returns: A random value within the bounds of `range`.
@inlinable
public static func random(in range: ClosedRange<Self>) -> Self {
var g = SystemRandomNumberGenerator()
return Self.random(in: range, using: &g)
}
}
//===----------------------------------------------------------------------===//
//===--- Operators on FixedWidthInteger -----------------------------------===//
//===----------------------------------------------------------------------===//
extension FixedWidthInteger {
/// Returns the inverse of the bits set in the argument.
///
/// The bitwise NOT operator (`~`) is a prefix operator that returns a value
/// in which all the bits of its argument are flipped: Bits that are `1` in
/// the argument are `0` in the result, and bits that are `0` in the argument
/// are `1` in the result. This is equivalent to the inverse of a set. For
/// example:
///
/// let x: UInt8 = 5 // 0b00000101
/// let notX = ~x // 0b11111010
///
/// Performing a bitwise NOT operation on 0 returns a value with every bit
/// set to `1`.
///
/// let allOnes = ~UInt8.min // 0b11111111
///
/// - Complexity: O(1).
@_transparent
public static prefix func ~ (x: Self) -> Self {
return 0 &- x &- 1
}
//===----------------------------------------------------------------------===//
//=== "Smart right shift", supporting overshifts and negative shifts ------===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the right.
///
/// The `>>` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a left shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*. An overshift results in `-1` for a
/// negative value of `lhs` or `0` for a nonnegative value.
/// - Using any other value for `rhs` performs a right shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted right by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x >> 2
/// // y == 7 // 0b00000111
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x >> 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a left shift
/// using `abs(rhs)`.
///
/// let a = x >> -3
/// // a == 240 // 0b11110000
/// let b = x << 3
/// // b == 240 // 0b11110000
///
/// Right shift operations on negative values "fill in" the high bits with
/// ones instead of zeros.
///
/// let q: Int8 = -30 // 0b11100010
/// let r = q >> 2
/// // r == -8 // 0b11111000
///
/// let s = q >> 11
/// // s == -1 // 0b11111111
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the right.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func >> <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
var lhs = lhs
_nonMaskingRightShiftGeneric(&lhs, rhs)
return lhs
}
@_transparent
@_semantics("optimize.sil.specialize.generic.partial.never")
public static func >>= <
Other: BinaryInteger
>(lhs: inout Self, rhs: Other) {
_nonMaskingRightShiftGeneric(&lhs, rhs)
}
@_transparent
public static func _nonMaskingRightShiftGeneric <
Other: BinaryInteger
>(_ lhs: inout Self, _ rhs: Other) {
let shift = rhs < -Self.bitWidth ? -Self.bitWidth
: rhs > Self.bitWidth ? Self.bitWidth
: Int(rhs)
lhs = _nonMaskingRightShift(lhs, shift)
}
@_transparent
public static func _nonMaskingRightShift(_ lhs: Self, _ rhs: Int) -> Self {
let overshiftR = Self.isSigned ? lhs &>> (Self.bitWidth - 1) : 0
let overshiftL: Self = 0
if _fastPath(rhs >= 0) {
if _fastPath(rhs < Self.bitWidth) {
return lhs &>> Self(truncatingIfNeeded: rhs)
}
return overshiftR
}
if _slowPath(rhs <= -Self.bitWidth) {
return overshiftL
}
return lhs &<< -rhs
}
//===----------------------------------------------------------------------===//
//=== "Smart left shift", supporting overshifts and negative shifts -------===//
//===----------------------------------------------------------------------===//
/// Returns the result of shifting a value's binary representation the
/// specified number of digits to the left.
///
/// The `<<` operator performs a *smart shift*, which defines a result for a
/// shift of any value.
///
/// - Using a negative value for `rhs` performs a right shift using
/// `abs(rhs)`.
/// - Using a value for `rhs` that is greater than or equal to the bit width
/// of `lhs` is an *overshift*, resulting in zero.
/// - Using any other value for `rhs` performs a left shift on `lhs` by that
/// amount.
///
/// The following example defines `x` as an instance of `UInt8`, an 8-bit,
/// unsigned integer type. If you use `2` as the right-hand-side value in an
/// operation on `x`, the value is shifted left by two bits.
///
/// let x: UInt8 = 30 // 0b00011110
/// let y = x << 2
/// // y == 120 // 0b01111000
///
/// If you use `11` as `rhs`, `x` is overshifted such that all of its bits
/// are set to zero.
///
/// let z = x << 11
/// // z == 0 // 0b00000000
///
/// Using a negative value as `rhs` is the same as performing a right shift
/// with `abs(rhs)`.
///
/// let a = x << -3
/// // a == 3 // 0b00000011
/// let b = x >> 3
/// // b == 3 // 0b00000011
///
/// - Parameters:
/// - lhs: The value to shift.
/// - rhs: The number of bits to shift `lhs` to the left.
@_semantics("optimize.sil.specialize.generic.partial.never")
@_transparent
public static func << <
Other: BinaryInteger
>(lhs: Self, rhs: Other) -> Self {
var lhs = lhs
_nonMaskingLeftShiftGeneric(&lhs, rhs)
return lhs
}
@_transparent
@_semantics("optimize.sil.specialize.generic.partial.never")
public static func <<= <
Other: BinaryInteger
>(lhs: inout Self, rhs: Other) {
_nonMaskingLeftShiftGeneric(&lhs, rhs)
}
@_transparent
public static func _nonMaskingLeftShiftGeneric <
Other: BinaryInteger
>(_ lhs: inout Self, _ rhs: Other) {
let shift = rhs < -Self.bitWidth ? -Self.bitWidth
: rhs > Self.bitWidth ? Self.bitWidth
: Int(rhs)
lhs = _nonMaskingLeftShift(lhs, shift)
}
@_transparent
public static func _nonMaskingLeftShift(_ lhs: Self, _ rhs: Int) -> Self {
let overshiftR = Self.isSigned ? lhs &>> (Self.bitWidth - 1) : 0
let overshiftL: Self = 0
if _fastPath(rhs >= 0) {
if _fastPath(rhs < Self.bitWidth) {
return lhs &<< Self(truncatingIfNeeded: rhs)
}
return overshiftL
}
if _slowPath(rhs <= -Self.bitWidth) {
return overshiftR
}
return lhs &>> -rhs
}
}
extension FixedWidthInteger {
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
public // @testable
static func _convert<Source: BinaryFloatingPoint>(
from source: Source
) -> (value: Self?, exact: Bool) {
guard _fastPath(!source.isZero) else { return (0, true) }
guard _fastPath(source.isFinite) else { return (nil, false) }
guard Self.isSigned || source > -1 else { return (nil, false) }
let exponent = source.exponent
if _slowPath(Self.bitWidth <= exponent) { return (nil, false) }
let minBitWidth = source.significandWidth
let isExact = (minBitWidth <= exponent)
let bitPattern = source.significandBitPattern
// Determine the actual number of fractional significand bits.
// `Source.significandBitCount` would not reflect the actual number of
// fractional significand bits if `Source` is not a fixed-width floating-point
// type; we can compute this value as follows if `source` is finite:
let bitWidth = minBitWidth &+ bitPattern.trailingZeroBitCount
let shift = exponent - Source.Exponent(bitWidth)
// Use `Self.Magnitude` to prevent sign extension if `shift < 0`.
let shiftedBitPattern = Self.Magnitude.bitWidth > bitWidth
? Self.Magnitude(truncatingIfNeeded: bitPattern) << shift
: Self.Magnitude(truncatingIfNeeded: bitPattern << shift)
if _slowPath(Self.isSigned && Self.bitWidth &- 1 == exponent) {
return source < 0 && shiftedBitPattern == 0
? (Self.min, isExact)
: (nil, false)
}
let magnitude = ((1 as Self.Magnitude) << exponent) | shiftedBitPattern
return (
Self.isSigned && source < 0 ? 0 &- Self(magnitude) : Self(magnitude),
isExact)
}
/// Creates an integer from the given floating-point value, rounding toward
/// zero. Any fractional part of the value passed as `source` is removed.
///
/// let x = Int(21.5)
/// // x == 21
/// let y = Int(-21.5)
/// // y == -21
///
/// If `source` is outside the bounds of this type after rounding toward
/// zero, a runtime error may occur.
///
/// let z = UInt(-21.5)
/// // Error: ...outside the representable range
///
/// - Parameter source: A floating-point value to convert to an integer.
/// `source` must be representable in this type after rounding toward
/// zero.
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
@inline(__always)
public init<T: BinaryFloatingPoint>(_ source: T) {
guard let value = Self._convert(from: source).value else {
fatalError("""
\(T.self) value cannot be converted to \(Self.self) because it is \
outside the representable range
""")
}
self = value
}
/// Creates an integer from the given floating-point value, if it can be
/// represented exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `21.0`, while the attempt to initialize the
/// constant `y` from `21.5` fails:
///
/// let x = Int(exactly: 21.0)
/// // x == Optional(21)
/// let y = Int(exactly: 21.5)
/// // y == nil
///
/// - Parameter source: A floating-point value to convert to an integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable
public init?<T: BinaryFloatingPoint>(exactly source: T) {
let (temporary, exact) = Self._convert(from: source)
guard exact, let value = temporary else {
return nil
}
self = value
}
/// Creates a new instance with the representable value that's closest to the
/// given integer.
///
/// If the value passed as `source` is greater than the maximum representable
/// value in this type, the result is the type's `max` value. If `source` is
/// less than the smallest representable value in this type, the result is
/// the type's `min` value.
///
/// In this example, `x` is initialized as an `Int8` instance by clamping
/// `500` to the range `-128...127`, and `y` is initialized as a `UInt`
/// instance by clamping `-500` to the range `0...UInt.max`.
///
/// let x = Int8(clamping: 500)
/// // x == 127
/// // x == Int8.max
///
/// let y = UInt(clamping: -500)
/// // y == 0
///
/// - Parameter source: An integer to convert to this type.
@inlinable
@_semantics("optimize.sil.specialize.generic.partial.never")
public init<Other: BinaryInteger>(clamping source: Other) {
if _slowPath(source < Self.min) {
self = Self.min
}
else if _slowPath(source > Self.max) {
self = Self.max
}
else { self = Self(truncatingIfNeeded: source) }
}
/// Creates a new instance from the bit pattern of the given instance by
/// truncating or sign-extending if needed to fit this type.
///
/// When the bit width of `T` (the type of `source`) is equal to or greater
/// than this type's bit width, the result is the truncated
/// least-significant bits of `source`. For example, when converting a
/// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are
/// used.
///
/// let p: Int16 = -500
/// // 'p' has a binary representation of 11111110_00001100
/// let q = Int8(truncatingIfNeeded: p)
/// // q == 12
/// // 'q' has a binary representation of 00001100
///
/// When the bit width of `T` is less than this type's bit width, the result
/// is *sign-extended* to fill the remaining bits. That is, if `source` is
/// negative, the result is padded with ones; otherwise, the result is
/// padded with zeros.
///
/// let u: Int8 = 21
/// // 'u' has a binary representation of 00010101
/// let v = Int16(truncatingIfNeeded: u)
/// // v == 21
/// // 'v' has a binary representation of 00000000_00010101
///
/// let w: Int8 = -21
/// // 'w' has a binary representation of 11101011
/// let x = Int16(truncatingIfNeeded: w)
/// // x == -21
/// // 'x' has a binary representation of 11111111_11101011
/// let y = UInt16(truncatingIfNeeded: w)
/// // y == 65515
/// // 'y' has a binary representation of 11111111_11101011
///
/// - Parameter source: An integer to convert to this type.
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T: BinaryInteger>(truncatingIfNeeded source: T) {
if Self.bitWidth <= Int.bitWidth {
self = Self(_truncatingBits: source._lowWord)
}
else {
let neg = source < (0 as T)
var result: Self = neg ? ~0 : 0
var shift: Self = 0
let width = Self(_truncatingBits: Self.bitWidth._lowWord)
for word in source.words {
guard shift < width else { break }
// Masking shift is OK here because we have already ensured
// that shift < Self.bitWidth. Not masking results in
// infinite recursion.
result ^= Self(_truncatingBits: neg ? ~word : word) &<< shift
shift += Self(_truncatingBits: Int.bitWidth._lowWord)
}
self = result
}
}
@_transparent
public // transparent
static var _highBitIndex: Self {
return Self.init(_truncatingBits: UInt(Self.bitWidth._value) &- 1)
}
/// Returns the sum of the two given values, wrapping the result in case of
/// any overflow.
///
/// The overflow addition operator (`&+`) discards any bits that overflow the
/// fixed width of the integer type. In the following example, the sum of
/// `100` and `121` is greater than the maximum representable `Int8` value,
/// so the result is the partial value after discarding the overflowing
/// bits.
///
/// let x: Int8 = 10 &+ 21
/// // x == 31
/// let y: Int8 = 100 &+ 121
/// // y == -35 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@_transparent
public static func &+ (lhs: Self, rhs: Self) -> Self {
return lhs.addingReportingOverflow(rhs).partialValue
}
/// Adds two values and stores the result in the left-hand-side variable,
/// wrapping any overflow.
///
/// The masking addition assignment operator (`&+=`) silently wraps any
/// overflow that occurs during the operation. In the following example, the
/// sum of `100` and `121` is greater than the maximum representable `Int8`
/// value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// var x: Int8 = 10
/// x &+= 21
/// // x == 31
/// var y: Int8 = 100
/// y &+= 121
/// // y == -35 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to add.
/// - rhs: The second value to add.
@_transparent
public static func &+= (lhs: inout Self, rhs: Self) {
lhs = lhs &+ rhs
}
/// Returns the difference of the two given values, wrapping the result in
/// case of any overflow.
///
/// The overflow subtraction operator (`&-`) discards any bits that overflow
/// the fixed width of the integer type. In the following example, the
/// difference of `10` and `21` is less than zero, the minimum representable
/// `UInt` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// let x: UInt8 = 21 &- 10
/// // x == 11
/// let y: UInt8 = 10 &- 21
/// // y == 245 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@_transparent
public static func &- (lhs: Self, rhs: Self) -> Self {
return lhs.subtractingReportingOverflow(rhs).partialValue
}
/// Subtracts the second value from the first and stores the difference in the
/// left-hand-side variable, wrapping any overflow.
///
/// The masking subtraction assignment operator (`&-=`) silently wraps any
/// overflow that occurs during the operation. In the following example, the
/// difference of `10` and `21` is less than zero, the minimum representable
/// `UInt` value, so the result is the result is the partial value after
/// discarding the overflowing bits.
///
/// var x: Int8 = 21
/// x &-= 10
/// // x == 11
/// var y: UInt8 = 10
/// y &-= 21
/// // y == 245 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: A numeric value.
/// - rhs: The value to subtract from `lhs`.
@_transparent
public static func &-= (lhs: inout Self, rhs: Self) {
lhs = lhs &- rhs
}
/// Returns the product of the two given values, wrapping the result in case
/// of any overflow.
///
/// The overflow multiplication operator (`&*`) discards any bits that
/// overflow the fixed width of the integer type. In the following example,
/// the product of `10` and `50` is greater than the maximum representable
/// `Int8` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// let x: Int8 = 10 &* 5
/// // x == 50
/// let y: Int8 = 10 &* 50
/// // y == -12 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
@_transparent
public static func &* (lhs: Self, rhs: Self) -> Self {
return lhs.multipliedReportingOverflow(by: rhs).partialValue
}
/// Multiplies two values and stores the result in the left-hand-side
/// variable, wrapping any overflow.
///
/// The masking multiplication assignment operator (`&*=`) silently wraps
/// any overflow that occurs during the operation. In the following example,
/// the product of `10` and `50` is greater than the maximum representable
/// `Int8` value, so the result is the partial value after discarding the
/// overflowing bits.
///
/// var x: Int8 = 10
/// x &*= 5
/// // x == 50
/// var y: Int8 = 10
/// y &*= 50
/// // y == -12 (after overflow)
///
/// For more about arithmetic with overflow operators, see [Overflow
/// Operators][overflow] in *[The Swift Programming Language][tspl]*.
///
/// [overflow]: https://docs.swift.org/swift-book/LanguageGuide/AdvancedOperators.html#ID37
/// [tspl]: https://docs.swift.org/swift-book/
///
/// - Parameters:
/// - lhs: The first value to multiply.
/// - rhs: The second value to multiply.
@_transparent
public static func &*= (lhs: inout Self, rhs: Self) {
lhs = lhs &* rhs
}
}
extension FixedWidthInteger {
@inlinable
public static func _random<R: RandomNumberGenerator>(
using generator: inout R
) -> Self {
if bitWidth <= UInt64.bitWidth {
return Self(truncatingIfNeeded: generator.next())
}
let (quotient, remainder) = bitWidth.quotientAndRemainder(
dividingBy: UInt64.bitWidth
)
var tmp: Self = 0
for i in 0 ..< quotient + remainder.signum() {
let next: UInt64 = generator.next()
tmp += Self(truncatingIfNeeded: next) &<< (UInt64.bitWidth * i)
}
return tmp
}
}
//===----------------------------------------------------------------------===//
//===--- UnsignedInteger --------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that can represent only nonnegative values.
public protocol UnsignedInteger: BinaryInteger { }
extension UnsignedInteger {
/// The magnitude of this value.
///
/// Every unsigned integer is its own magnitude, so for any value `x`,
/// `x == x.magnitude`.
///
/// The global `abs(_:)` function provides more familiar syntax when you need
/// to find an absolute value. In addition, because `abs(_:)` always returns
/// a value of the same type, even in a generic context, using the function
/// instead of the `magnitude` property is encouraged.
@inlinable // FIXME(inline-always)
public var magnitude: Self {
@inline(__always)
get { return self }
}
/// A Boolean value indicating whether this type is a signed integer type.
///
/// This property is always `false` for unsigned integer types.
@inlinable // FIXME(inline-always)
public static var isSigned: Bool {
@inline(__always)
get { return false }
}
}
extension UnsignedInteger where Self: FixedWidthInteger {
/// Creates a new instance from the given integer.
///
/// Use this initializer to convert from another integer type when you know
/// the value is within the bounds of this type. Passing a value that can't
/// be represented in this type results in a runtime error.
///
/// In the following example, the constant `y` is successfully created from
/// `x`, an `Int` instance with a value of `100`. Because the `Int8` type
/// can represent `127` at maximum, the attempt to create `z` with a value
/// of `1000` results in a runtime error.
///
/// let x = 100
/// let y = Int8(x)
/// // y == 100
/// let z = Int8(x * 10)
/// // Error: Not enough bits to represent the given value
///
/// - Parameter source: A value to convert to this type of integer. The value
/// passed as `source` must be representable in this type.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T: BinaryInteger>(_ source: T) {
// This check is potentially removable by the optimizer
if T.isSigned {
_precondition(source >= (0 as T), "Negative value is not representable")
}
// This check is potentially removable by the optimizer
if source.bitWidth >= Self.bitWidth {
_precondition(source <= Self.max,
"Not enough bits to represent the passed value")
}
self.init(truncatingIfNeeded: source)
}
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type of integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init?<T: BinaryInteger>(exactly source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source < (0 as T) {
return nil
}
// The width check can be eliminated by the optimizer
if source.bitWidth >= Self.bitWidth &&
source > Self.max {
return nil
}
self.init(truncatingIfNeeded: source)
}
/// The maximum representable integer in this type.
///
/// For unsigned integer types, this value is `(2 ** bitWidth) - 1`, where
/// `**` is exponentiation.
@_transparent
public static var max: Self { return ~0 }
/// The minimum representable integer in this type.
///
/// For unsigned integer types, this value is always `0`.
@_transparent
public static var min: Self { return 0 }
}
//===----------------------------------------------------------------------===//
//===--- SignedInteger ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// An integer type that can represent both positive and negative values.
public protocol SignedInteger: BinaryInteger, SignedNumeric {
// These requirements are for the source code compatibility with Swift 3
static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self
static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self
}
extension SignedInteger {
/// A Boolean value indicating whether this type is a signed integer type.
///
/// This property is always `true` for signed integer types.
@inlinable // FIXME(inline-always)
public static var isSigned: Bool {
@inline(__always)
get { return true }
}
}
extension SignedInteger where Self: FixedWidthInteger {
/// Creates a new instance from the given integer.
///
/// Use this initializer to convert from another integer type when you know
/// the value is within the bounds of this type. Passing a value that can't
/// be represented in this type results in a runtime error.
///
/// In the following example, the constant `y` is successfully created from
/// `x`, an `Int` instance with a value of `100`. Because the `Int8` type
/// can represent `127` at maximum, the attempt to create `z` with a value
/// of `1000` results in a runtime error.
///
/// let x = 100
/// let y = Int8(x)
/// // y == 100
/// let z = Int8(x * 10)
/// // Error: Not enough bits to represent the given value
///
/// - Parameter source: A value to convert to this type of integer. The value
/// passed as `source` must be representable in this type.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init<T: BinaryInteger>(_ source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source.bitWidth > Self.bitWidth {
_precondition(source >= Self.min,
"Not enough bits to represent a signed value")
}
// This check is potentially removable by the optimizer
if (source.bitWidth > Self.bitWidth) ||
(source.bitWidth == Self.bitWidth && !T.isSigned) {
_precondition(source <= Self.max,
"Not enough bits to represent the passed value")
}
self.init(truncatingIfNeeded: source)
}
/// Creates a new instance from the given integer, if it can be represented
/// exactly.
///
/// If the value passed as `source` is not representable exactly, the result
/// is `nil`. In the following example, the constant `x` is successfully
/// created from a value of `100`, while the attempt to initialize the
/// constant `y` from `1_000` fails because the `Int8` type can represent
/// `127` at maximum:
///
/// let x = Int8(exactly: 100)
/// // x == Optional(100)
/// let y = Int8(exactly: 1_000)
/// // y == nil
///
/// - Parameter source: A value to convert to this type of integer.
@_semantics("optimize.sil.specialize.generic.partial.never")
@inlinable // FIXME(inline-always)
@inline(__always)
public init?<T: BinaryInteger>(exactly source: T) {
// This check is potentially removable by the optimizer
if T.isSigned && source.bitWidth > Self.bitWidth && source < Self.min {
return nil
}
// The width check can be eliminated by the optimizer
if (source.bitWidth > Self.bitWidth ||
(source.bitWidth == Self.bitWidth && !T.isSigned)) &&
source > Self.max {
return nil
}
self.init(truncatingIfNeeded: source)
}
/// The maximum representable integer in this type.
///
/// For signed integer types, this value is `(2 ** (bitWidth - 1)) - 1`,
/// where `**` is exponentiation.
@_transparent
public static var max: Self { return ~min }
/// The minimum representable integer in this type.
///
/// For signed integer types, this value is `-(2 ** (bitWidth - 1))`, where
/// `**` is exponentiation.
@_transparent
public static var min: Self {
return (-1 as Self) &<< Self._highBitIndex
}
@inlinable
public func isMultiple(of other: Self) -> Bool {
// Nothing but zero is a multiple of zero.
if other == 0 { return self == 0 }
// Special case to avoid overflow on .min / -1 for signed types.
if other == -1 { return true }
// Having handled those special cases, this is safe.
return self % other == 0
}
}
/// Returns the given integer as the equivalent value in a different integer
/// type.
///
/// Calling the `numericCast(_:)` function is equivalent to calling an
/// initializer for the destination type. `numericCast(_:)` traps on overflow
/// in `-O` and `-Onone` builds.
///
/// - Parameter x: The integer to convert, an instance of type `T`.
/// - Returns: The value of `x` converted to type `U`.
@inlinable
public func numericCast<T: BinaryInteger, U: BinaryInteger>(_ x: T) -> U {
return U(x)
}
// FIXME(integers): Absence of &+ causes ambiguity in the code like the
// following:
// func f<T: SignedInteger>(_ x: T, _ y: T) {
// var _ = (x &+ (y - 1)) < x
// }
// Compiler output:
// error: ambiguous reference to member '-'
// var _ = (x &+ (y - 1)) < x
// ^
extension SignedInteger {
@_transparent
public static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self {
fatalError("Should be overridden in a more specific type")
}
@_transparent
public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self {
fatalError("Should be overridden in a more specific type")
}
}
extension SignedInteger where Self: FixedWidthInteger {
// This overload is supposed to break the ambiguity between the
// implementations on SignedInteger and FixedWidthInteger
@_transparent
public static func &+ (lhs: Self, rhs: Self) -> Self {
return _maskingAdd(lhs, rhs)
}
@_transparent
public static func _maskingAdd(_ lhs: Self, _ rhs: Self) -> Self {
return lhs.addingReportingOverflow(rhs).partialValue
}
// This overload is supposed to break the ambiguity between the
// implementations on SignedInteger and FixedWidthInteger
@_transparent
public static func &- (lhs: Self, rhs: Self) -> Self {
return _maskingSubtract(lhs, rhs)
}
@_transparent
public static func _maskingSubtract(_ lhs: Self, _ rhs: Self) -> Self {
return lhs.subtractingReportingOverflow(rhs).partialValue
}
}
|
apache-2.0
|
03db08bdf146dd150ef1eeb0801a5f68
| 37.282798 | 93 | 0.594358 | 4.069056 | false | false | false | false |
OEASLAN/LetsEat
|
IOS/Let's Eat/Let's Eat/Entry VC/SignupVC.swift
|
1
|
7163
|
//
// SigupVC.swift
// login
//
// Created by VidalHARA on 1.11.2014.
// Copyright (c) 2014 MacBook Retina. All rights reserved.
//
import UIKit
class SignupVC: UIViewController {
@IBOutlet weak var textName: UITextField!
@IBOutlet weak var textSurname: UITextField!
@IBOutlet weak var textUsername: UITextField!
@IBOutlet weak var textEmail: UITextField!
@IBOutlet weak var textPassword: UITextField!
@IBOutlet weak var textConfirmPassword: UITextField!
@IBOutlet weak var passwordCheck: UIButton!
@IBOutlet weak var passwordConfirmCheck: UIButton!
let apiMethod = ApiMethods()
let alert = Alerts()
override func viewWillAppear(animated: Bool) {
let bgSetter = BackgroundSetter(viewControler: self)
bgSetter.getBackgroundView()
}
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
self.view.endEditing(true)
}
@IBAction func nextKey(sender: UITextField) {
if sender == textName{
textSurname.becomeFirstResponder()
}else if sender == textSurname{
textUsername.becomeFirstResponder()
}else if sender == textUsername{
textEmail.becomeFirstResponder()
}else if sender == textEmail{
textPassword.becomeFirstResponder()
}else if sender == textPassword{
textConfirmPassword.becomeFirstResponder()
}else {
signupTapped()
self.view.endEditing(true)
}
}
@IBOutlet weak var scrollView: UIScrollView!
@IBAction func scrollForEditing(sender: UITextField) {
// If it is in landscape
if sender == textPassword {
scrollView.setContentOffset(CGPointMake(0, 20), animated: true)
}
}
@IBAction func signupTapped() {
self.view.endEditing(true)
var name:NSString = textName.text as NSString
var surname:NSString = textSurname.text as NSString
var username:NSString = textUsername.text as NSString
var email:NSString = textEmail.text as NSString
var password:NSString = textPassword.text as NSString
var confirm_password:NSString = textConfirmPassword.text as NSString
if ( name.isEqualToString("") || surname.isEqualToString("") || username.isEqualToString("") || password.isEqualToString("") || confirm_password.isEqualToString("") || email.isEqualToString("")) {
alert.emptyFieldError("Sign Up Failed!", vc: self)
}else if !isEmailValid(email as String){
alert.unValidEmailError("Sign Up Failed!", vc: self)
}else if password != confirm_password {
alert.confirmError("Sign Up Failed!", vc: self)
}else if !isPasswordValid() {
alert.unValidPasswordError("Sign Up Failed!", vc: self)
}else {
var post:NSString = "name=\(name)&surname=\(surname)&email=\(email)&password=\(password)&username=\(username)"
NSLog("PostData: %@",post);
var url:NSURL = NSURL(string: "http://127.0.0.1:8000/api/register/")!
var request = apiMethod.getRequest(url, post: post)
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let jsonData = apiMethod.getJsonData(urlData!)
let success:NSString = jsonData.valueForKey("status") as! String
//[jsonData[@"success"] integerValue];
NSLog("Success: %ld", success);
if(success == "success")
{
NSLog("Sign Up SUCCESS");
self.dismissViewControllerAnimated(true, completion: nil)
} else {
alert.getSuccesError(jsonData, str: "Sign up Failed!", vc: self)
}
} else {
alert.getStatusCodeError("Sign up Failed!", vc: self)
}
} else {
alert.getUrlDataError(reponseError, str: "Sign up Failed!", vc: self)
}
}
}
@IBAction func passwordImageCheck() {
if isPasswordValid() {
passwordConfirmCheck.hidden = false
passwordCheck.hidden = false
}else{
passwordConfirmCheck.hidden = true
passwordCheck.hidden = true
}
}
@IBAction func backToLogin() {
self.dismissViewControllerAnimated(true, completion: nil)
}
func isPasswordValid() -> Bool {
var passwordConfirmTxt: NSString = textConfirmPassword.text
if (passwordConfirmTxt.length >= 6 ){
var passwordTxt: NSString = textPassword.text
if(passwordTxt == passwordConfirmTxt){
if (passwordTxt.rangeOfCharacterFromSet(NSCharacterSet.uppercaseLetterCharacterSet()).location != NSNotFound && passwordTxt.rangeOfCharacterFromSet(NSCharacterSet.lowercaseLetterCharacterSet()).location != NSNotFound && passwordTxt.rangeOfCharacterFromSet(NSCharacterSet.decimalDigitCharacterSet()).location != NSNotFound){
return true
}
}
}
return false
}
//Düzelt burayı
func isEmailValid(email:String) -> Bool {
/*let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"
if let emailTest = NSPredicate() NSPredicate(format: "SELF MATCHES %@", arguments: emailRegEx)) {
return emailTest.evaluateWithObject(email)
}
return false*/
return true
}
/*
func userError(){
var alertView:UIAlertView = UIAlertView()
alertView.title = "Sign Up Failed!"
alertView.message = "There is an user which has same username with you. Please change your username!"
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
gpl-2.0
|
0db448770346b480e23f1d774f35ca58
| 34.102941 | 339 | 0.568915 | 5.396383 | false | false | false | false |
huangboju/Eyepetizer
|
Eyepetizer/Eyepetizer/Views/LaunchView.swift
|
1
|
1412
|
//
// EYELaunchView.swift
// EyepetizerApp
//
// Created by 梁亦明 on 16/4/8.
// Copyright © 2016年 xiaoming. All rights reserved.
//
import UIKit
class LaunchView: UIView {
// 图片
@IBOutlet weak var imageView: UIImageView!
// 黑色背景
@IBOutlet weak var blackBgView: UIView!
// 动画完成回调
typealias AnimationDidStopCallBack = (launchView: LaunchView) -> Void
var callBack : AnimationDidStopCallBack?
class func launchView() -> LaunchView {
return NSBundle.mainBundle().loadNibNamed("LaunchView", owner: nil, options: nil).first as! LaunchView
}
override func awakeFromNib() {
super.awakeFromNib()
startAnimation()
}
// 黑色背景渐变动画和图片放大动画
private func startAnimation() {
UIView.animateWithDuration(5, delay: 1, options: .CurveEaseInOut, animations: {
self.imageView.transform = CGAffineTransformMakeScale(1.5, 1.5)
self.blackBgView.alpha = 0
}) { [unowned self](_) in
self.blackBgView.removeFromSuperview()
if let cb = self.callBack {
cb(launchView: self)
}
}
}
/**
动画完成时回调
*/
func animationDidStop(callBack: AnimationDidStopCallBack?) {
self.callBack = callBack
}
}
|
mit
|
e18e8729c0287e4e9fdc56a1b99f5d40
| 25.176471 | 110 | 0.594007 | 4.45 | false | false | false | false |
onevcat/Kingfisher
|
Sources/Extensions/CPListItem+Kingfisher.swift
|
2
|
11170
|
//
// CPListItem+Kingfisher.swift
// Kingfisher
//
// Created by Wayne Hartman on 2021-08-29.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if canImport(CarPlay) && !targetEnvironment(macCatalyst)
import CarPlay
@available(iOS 14.0, *)
extension KingfisherWrapper where Base: CPListItem {
// MARK: Setting Image
/// Sets an image to the image view with a source.
///
/// - Parameters:
/// - source: The `Source` object contains information about the image.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
///
/// Internally, this method will use `KingfisherManager` to get the requested source
/// Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
let options = KingfisherParsedOptionsInfo(KingfisherManager.shared.defaultOptions + (options ?? []))
return setImage(
with: source,
placeholder: placeholder,
parsedOptions: options,
progressBlock: progressBlock,
completionHandler: completionHandler
)
}
/// Sets an image to the image view with a requested resource.
///
/// - Parameters:
/// - resource: The `Resource` object contains information about the image.
/// - placeholder: A placeholder to show while retrieving the image from the given `resource`.
/// - options: An options set to define image setting behaviors. See `KingfisherOptionsInfo` for more.
/// - progressBlock: Called when the image downloading progress gets updated. If the response does not contain an
/// `expectedContentLength`, this block will not be called.
/// - completionHandler: Called when the image retrieved and set finished.
/// - Returns: A task represents the image downloading.
///
/// - Note:
///
/// Internally, this method will use `KingfisherManager` to get the requested resource, from either cache
/// or network. Since this method will perform UI changes, you must call it from the main thread.
/// Both `progressBlock` and `completionHandler` will be also executed in the main thread.
///
@discardableResult
public func setImage(
with resource: Resource?,
placeholder: KFCrossPlatformImage? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
return setImage(
with: resource?.convertToSource(),
placeholder: placeholder,
options: options,
progressBlock: progressBlock,
completionHandler: completionHandler)
}
func setImage(
with source: Source?,
placeholder: KFCrossPlatformImage? = nil,
parsedOptions: KingfisherParsedOptionsInfo,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: ((Result<RetrieveImageResult, KingfisherError>) -> Void)? = nil) -> DownloadTask?
{
var mutatingSelf = self
guard let source = source else {
/**
* In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
* to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
* which allows >=14.5 SDK to set a `nil` image. This compile check allows
* newer SDK users to set the image to `nil`, while still allowing older SDK
* users to compile the framework.
*/
#if compiler(>=5.4)
self.base.setImage(placeholder)
#else
if let placeholder = placeholder {
self.base.setImage(placeholder)
}
#endif
mutatingSelf.taskIdentifier = nil
completionHandler?(.failure(KingfisherError.imageSettingError(reason: .emptySource)))
return nil
}
var options = parsedOptions
if !options.keepCurrentImageWhileLoading {
/**
* In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
* to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
* which allows >=14.5 SDK to set a `nil` image. This compile check allows
* newer SDK users to set the image to `nil`, while still allowing older SDK
* users to compile the framework.
*/
#if compiler(>=5.4)
self.base.setImage(placeholder)
#else // Let older SDK users deal with the older behavior.
if let placeholder = placeholder {
self.base.setImage(placeholder)
}
#endif
}
let issuedIdentifier = Source.Identifier.next()
mutatingSelf.taskIdentifier = issuedIdentifier
if let block = progressBlock {
options.onDataReceived = (options.onDataReceived ?? []) + [ImageLoadingProgressSideEffect(block)]
}
let task = KingfisherManager.shared.retrieveImage(
with: source,
options: options,
downloadTaskUpdated: { mutatingSelf.imageTask = $0 },
progressiveImageSetter: { self.base.setImage($0) },
referenceTaskIdentifierChecker: { issuedIdentifier == self.taskIdentifier },
completionHandler: { result in
CallbackQueue.mainCurrentOrAsync.execute {
guard issuedIdentifier == self.taskIdentifier else {
let reason: KingfisherError.ImageSettingErrorReason
do {
let value = try result.get()
reason = .notCurrentSourceTask(result: value, error: nil, source: source)
} catch {
reason = .notCurrentSourceTask(result: nil, error: error, source: source)
}
let error = KingfisherError.imageSettingError(reason: reason)
completionHandler?(.failure(error))
return
}
mutatingSelf.imageTask = nil
mutatingSelf.taskIdentifier = nil
switch result {
case .success(let value):
self.base.setImage(value.image)
completionHandler?(result)
case .failure:
if let image = options.onFailureImage {
/**
* In iOS SDK 14.0-14.4 the image param was non-`nil`. The SDK changed in 14.5
* to allow `nil`. The compiler version 5.4 was introduced in this same SDK,
* which allows >=14.5 SDK to set a `nil` image. This compile check allows
* newer SDK users to set the image to `nil`, while still allowing older SDK
* users to compile the framework.
*/
#if compiler(>=5.4)
self.base.setImage(image)
#else // Let older SDK users deal with the older behavior.
if let unwrapped = image {
self.base.setImage(unwrapped)
}
#endif
} else {
#if compiler(>=5.4)
self.base.setImage(nil)
#endif
}
completionHandler?(result)
}
}
}
)
mutatingSelf.imageTask = task
return task
}
// MARK: Cancelling Image
/// Cancel the image download task bounded to the image view if it is running.
/// Nothing will happen if the downloading has already finished.
public func cancelDownloadTask() {
imageTask?.cancel()
}
}
private var taskIdentifierKey: Void?
private var imageTaskKey: Void?
// MARK: Properties
extension KingfisherWrapper where Base: CPListItem {
public private(set) var taskIdentifier: Source.Identifier.Value? {
get {
let box: Box<Source.Identifier.Value>? = getAssociatedObject(base, &taskIdentifierKey)
return box?.value
}
set {
let box = newValue.map { Box($0) }
setRetainedAssociatedObject(base, &taskIdentifierKey, box)
}
}
private var imageTask: DownloadTask? {
get { return getAssociatedObject(base, &imageTaskKey) }
set { setRetainedAssociatedObject(base, &imageTaskKey, newValue)}
}
}
#endif
|
mit
|
3a09225468c975924d8ec8a8b976baf5
| 43.68 | 119 | 0.58299 | 5.505175 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureTransaction/Sources/FeatureTransactionUI/TargetSelectionPage/TargetSelectionPageInteractor.swift
|
1
|
15677
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import DIKit
import Localization
import MoneyKit
import PlatformKit
import PlatformUIKit
import RIBs
import RxCocoa
import RxSwift
import ToolKit
protocol TargetSelectionPageRouting: ViewableRouting {
func presentQRScanner(
sourceAccount: CryptoAccount,
model: TargetSelectionPageModel
)
}
protocol TargetSelectionPageListener: AnyObject {
func didSelect(target: TransactionTarget)
func didTapBack()
func didTapClose()
}
final class TargetSelectionPageInteractor: PresentableInteractor<TargetSelectionPagePresentable>,
TargetSelectionPageInteractable
{
weak var router: TargetSelectionPageRouting?
// MARK: - Private Properties
private let accountProvider: SourceAndTargetAccountProviding
private let targetSelectionPageModel: TargetSelectionPageModel
private let action: AssetAction
private let messageRecorder: MessageRecording
private let didSelect: AccountPickerDidSelect?
private let backButtonInterceptor: BackButtonInterceptor
private let radioSelectionHandler: RadioSelectionHandling
weak var listener: TargetSelectionPageListener?
// MARK: - Init
init(
targetSelectionPageModel: TargetSelectionPageModel,
presenter: TargetSelectionPagePresentable,
accountProvider: SourceAndTargetAccountProviding,
listener: TargetSelectionListenerBridge,
action: AssetAction,
radioSelectionHandler: RadioSelectionHandling,
backButtonInterceptor: @escaping BackButtonInterceptor,
messageRecorder: MessageRecording = resolve()
) {
self.action = action
self.targetSelectionPageModel = targetSelectionPageModel
self.accountProvider = accountProvider
self.messageRecorder = messageRecorder
self.backButtonInterceptor = backButtonInterceptor
self.radioSelectionHandler = radioSelectionHandler
switch listener {
case .simple(let didSelect):
self.didSelect = didSelect
self.listener = nil
case .listener(let listener):
didSelect = nil
self.listener = listener
}
super.init(presenter: presenter)
}
override func didBecomeActive() {
super.didBecomeActive()
let cryptoAddressViewModel = CryptoAddressTextFieldViewModel(
validator: CryptoAddressValidator(model: targetSelectionPageModel),
messageRecorder: messageRecorder
)
let transactionState = targetSelectionPageModel.state
.share(replay: 1, scope: .whileConnected)
// This returns an observable from the TransactionModel and its state.
// Since the TargetSelection has it's own model/state/actions we need to intercept when the back button
// of the TransactionFlow occurs and update the TargetSelection state
backButtonInterceptor()
.subscribe(onNext: { [weak self] state in
let hasCorrectBackStack = state.backStack.isEmpty || state.backStack.contains(.selectTarget)
let hasCorrectStep = state.step == .enterAmount || state.step == .selectTarget
if hasCorrectStep, hasCorrectBackStack, state.isGoingBack {
self?.targetSelectionPageModel.process(action: .returnToPreviousStep)
}
})
.disposeOnDeactivate(interactor: self)
/// Fetch the source account provided.
let sourceAccount = accountProvider.sourceAccount
.map { account -> BlockchainAccount in
guard let crypto = account else {
fatalError("Expected a source account")
}
return crypto
}
.asObservable()
.share(replay: 1, scope: .whileConnected)
/// Any text coming from the `State` we want to bind
/// to the `cryptoAddressViewModel` textRelay.
transactionState
.map(\.inputValidated)
.map(\.text)
.bind(to: cryptoAddressViewModel.originalTextRelay)
.disposeOnDeactivate(interactor: self)
let requiredValidationAction = transactionState
.map(\.inputValidated)
/// Only the QR scanner requires validation. The textfield
/// validates itself so long as it's in focus.
.filter(\.requiresValidation)
/// We get the text from the `State` and not the textField.
/// This is **only** for the QR scanner. This is to prevent
/// conflating text entry with QR scanning or deep linking.
.map(\.text)
.distinctUntilChanged()
requiredValidationAction
.withLatestFrom(sourceAccount) { ($0, $1) }
.observe(on: MainScheduler.asyncInstance)
.subscribe(onNext: { [weak self] text, account in
self?.targetSelectionPageModel.process(action: .validateAddress(text, account))
})
.disposeOnDeactivate(interactor: self)
/// The text the user has entered into the textField
let text = cryptoAddressViewModel
.text
.distinctUntilChanged()
/// Whether or not the textField is in focus
let isFocused = cryptoAddressViewModel
.focusRelay
/// We only want to update the `State` with a text entry value
/// when the text field is not in focus.
.map { $0 == .on }
// `textWhileTyping` stream the text field text while it has focus.
let textWhileTyping: Observable<String> = text
.withLatestFrom(isFocused) { ($0, $1) }
.filter(\.1)
.map(\.0)
.share(replay: 1, scope: .whileConnected)
// As soon as something is inputted, we want to disable the 'next' action.
textWhileTyping
.observe(on: MainScheduler.asyncInstance)
.subscribe(onNext: { [weak self] _ in
self?.targetSelectionPageModel.process(action: .destinationDeselected)
})
.disposeOnDeactivate(interactor: self)
// The stream is debounced and we then process the validation.
textWhileTyping
.debounce(.milliseconds(500), scheduler: ConcurrentDispatchQueueScheduler(qos: .userInitiated))
.withLatestFrom(sourceAccount) { ($0, $1) }
.observe(on: MainScheduler.asyncInstance)
.subscribe(onNext: { [weak self] text, account in
self?.targetSelectionPageModel.process(action: .validateAddress(text, account))
})
.disposeOnDeactivate(interactor: self)
/// Launch the QR scanner should the button be tapped
cryptoAddressViewModel
.tapRelay
.bindAndCatch(weak: self) { (self) in
self.targetSelectionPageModel.process(action: .qrScannerButtonTapped)
}
.disposeOnDeactivate(interactor: self)
/// Binding for radio selection state
let initialTargetsAction = transactionState
.map(\.availableTargets)
.map { $0.compactMap { $0 as? SingleAccount }.map(\.identifier) }
.distinctUntilChanged()
.map(RadioSelectionAction.initialValues)
let deselectAction = Observable.merge(textWhileTyping, requiredValidationAction)
.map { _ in RadioSelectionAction.deselectAll }
let radioSelectionAction = transactionState
// a selected input is inferred if the inputValidated is TargetSelectionInputValidation.account
.filter(\.inputValidated.isAccountSelection)
.compactMap { $0.destination as? SingleAccount }
.map(\.identifier)
.map(RadioSelectionAction.select)
Observable.merge(
initialTargetsAction,
deselectAction,
radioSelectionAction
)
.bind(to: radioSelectionHandler.selectionAction)
.disposeOnDeactivate(interactor: self)
/// Listens to the `step` which
/// triggers routing to a new screen or ending the flow
transactionState
.distinctUntilChanged(\.step)
.observe(on: MainScheduler.asyncInstance)
.subscribe(onNext: { [weak self] newState in
self?.handleStateChange(newState: newState)
})
.disposeOnDeactivate(interactor: self)
sourceAccount
.map(\.currencyType)
.map { currency -> String in
Self.addressFieldWarning(currency: currency)
}
.bind(to: cryptoAddressViewModel.subtitleRelay)
.disposeOnDeactivate(interactor: self)
sourceAccount
.subscribe(onNext: { [weak self] account in
guard let self = self else { return }
self.targetSelectionPageModel.process(action: .sourceAccountSelected(account, self.action))
})
.disposeOnDeactivate(interactor: self)
let interactorState = transactionState
.observe(on: MainScheduler.instance)
.scan(.empty) { [weak self] state, updater -> TargetSelectionPageInteractor.State in
guard let self = self else {
return state
}
guard updater.sourceAccount != nil else {
/// We cannot proceed to the calculation step without a `sourceAccount`
Logger.shared.debug("No sourceAccount: \(updater)")
return state
}
return self.calculateNextState(
with: state,
updater: updater,
cryptoAddressViewModel: cryptoAddressViewModel
)
}
.asDriverCatchError()
presenter.connect(state: interactorState)
.drive(onNext: handle(effects:))
.disposeOnDeactivate(interactor: self)
}
// MARK: - Private methods
private func calculateNextState(
with state: State,
updater: TargetSelectionPageState,
cryptoAddressViewModel: CryptoAddressTextFieldViewModel
) -> State {
guard let sourceAccount = updater.sourceAccount as? SingleAccount else {
fatalError("You should have a source account.")
}
var state = state
if state.sourceInteractor?.account.identifier != sourceAccount.identifier {
state = state
.update(
keyPath: \.sourceInteractor,
value: .singleAccount(sourceAccount, AccountAssetBalanceViewInteractor(account: sourceAccount))
)
}
if state.destinationInteractors.isEmpty {
let targets = updater.availableTargets.compactMap { $0 as? SingleAccount }
let destinations: [TargetSelectionPageCellItem.Interactor] = targets.map { account in
.singleAccountAvailableTarget(
RadioAccountCellInteractor(account: account, radioSelectionHandler: self.radioSelectionHandler)
)
}
.sorted { $0.account.label < $1.account.label }
state = state
.update(keyPath: \.destinationInteractors, value: destinations)
}
if state.inputFieldInteractor == nil {
state = state
.update(
keyPath: \.inputFieldInteractor,
value: .walletInputField(sourceAccount, cryptoAddressViewModel)
)
}
return state
/// Update the enabled state of the `Next` button.
.update(keyPath: \.actionButtonEnabled, value: updater.nextEnabled)
}
private func handle(effects: Effects) {
switch effects {
case .select(let account):
targetSelectionPageModel.process(action: .destinationSelected(account))
case .back,
.closed:
targetSelectionPageModel.process(action: .resetFlow)
case .next:
targetSelectionPageModel.process(action: .destinationConfirmed)
case .none:
break
}
}
private var initialStep: Bool = true
private func handleStateChange(newState: TargetSelectionPageState) {
if !initialStep, newState.step == TargetSelectionPageStep.initial {
// no-op
} else {
initialStep = false
showFlowStep(newState: newState)
}
}
private func finishFlow() {
targetSelectionPageModel.process(action: .resetFlow)
}
private func showFlowStep(newState: TargetSelectionPageState) {
guard !newState.isGoingBack else {
listener?.didTapBack()
return
}
switch newState.step {
case .initial:
break
case .closed:
targetSelectionPageModel.destroy()
listener?.didTapClose()
case .complete:
guard let account = newState.destination else {
fatalError("Expected a destination acount.")
}
didSelect?(account as! SingleAccount)
listener?.didSelect(target: account)
case .qrScanner:
guard let sourceAccount = newState.sourceAccount else {
fatalError("Expected a sourceAccount: \(newState)")
}
guard let cryptoAccount = sourceAccount as? CryptoAccount else {
fatalError("Expected a CryptoAccount: \(sourceAccount)")
}
router?.presentQRScanner(
sourceAccount: cryptoAccount,
model: targetSelectionPageModel
)
}
}
private func initialState() -> TargetSelectionPageState {
TargetSelectionPageState(nextEnabled: false, destination: nil)
}
private static func addressFieldWarning(currency: CurrencyType) -> String {
func defaultWarning() -> String {
LocalizationConstants.TextField.Title.sendToCryptoWallet(
displayCode: currency.displaySymbol,
networkName: currency.name
)
}
return addressFieldERC20Warning(currency: currency)
?? defaultWarning()
}
private static func addressFieldERC20Warning(currency: CurrencyType) -> String? {
let erc20ParentChain: AssetModelType.ERC20ParentChain? = currency
.cryptoCurrency?
.assetModel
.kind
.erc20ParentChain
return erc20ParentChain
.flatMap { chain -> String in
LocalizationConstants.TextField.Title.sendToCryptoWallet(
displayCode: currency.displaySymbol,
networkName: chain.name
)
}
}
}
extension TargetSelectionPageInteractor {
struct State: StateType {
static let empty = State(actionButtonEnabled: false)
var sourceInteractor: TargetSelectionPageCellItem.Interactor?
var inputFieldInteractor: TargetSelectionPageCellItem.Interactor?
var destinationInteractors: [TargetSelectionPageCellItem.Interactor]
var actionButtonEnabled: Bool
private init(actionButtonEnabled: Bool) {
self.actionButtonEnabled = actionButtonEnabled
sourceInteractor = nil
inputFieldInteractor = nil
destinationInteractors = []
}
}
enum Effects {
case select(BlockchainAccount)
case next
case back
case closed
case none
}
}
|
lgpl-3.0
|
89e7422a658c18eae3e617899e52d0f9
| 36.956416 | 115 | 0.621268 | 5.403654 | false | false | false | false |
huonw/swift
|
stdlib/public/core/StringObject.swift
|
1
|
24137
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// TODO: Comments. Supposed to abstract bit-twiddling operations. Meant to be a
// completely transparent struct. That is, it's just a trivial encapsulation to
// host many operations that would otherwise be scattered throughout StringGuts
// implementation.
//
@_fixed_layout
public // @testable
struct _StringObject {
// TODO: Proper built-in string object support.
#if arch(i386) || arch(arm)
// BridgeObject lacks support for tagged pointers on 32-bit platforms, and
// there are no free bits available to implement it. We use a single-word
// enum instead, with an additional word for holding tagged values and (in the
// non-tagged case) spilled flags.
@_frozen
@usableFromInline
internal enum _Variant {
case strong(AnyObject) // _bits stores flags
case unmanagedSingleByte // _bits is the start address
case unmanagedDoubleByte // _bits is the start address
case smallSingleByte // _bits is the payload
case smallDoubleByte // _bits is the payload
// TODO small strings
}
@usableFromInline
internal
var _variant: _Variant
@usableFromInline
internal
var _bits: UInt
#else
// On 64-bit platforms, we use BridgeObject for now. This might be very
// slightly suboptimal and different than hand-optimized bit patterns, but
// provides us the runtime functionality we want.
@usableFromInline
internal
var _object: Builtin.BridgeObject
#endif
#if arch(i386) || arch(arm)
@inlinable
@inline(__always)
internal
init(_ variant: _Variant, _ bits: UInt) {
self._variant = variant
self._bits = bits
_invariantCheck()
}
#else
@inlinable
@inline(__always)
internal
init(_ object: Builtin.BridgeObject) {
self._object = object
_invariantCheck()
}
#endif
}
extension _StringObject {
#if arch(i386) || arch(arm)
public typealias _RawBitPattern = UInt64
#else
public typealias _RawBitPattern = UInt
#endif
@inlinable
internal
var rawBits: _RawBitPattern {
@inline(__always)
get {
#if arch(i386) || arch(arm)
let variantBits: UInt = Builtin.reinterpretCast(_variant)
return _RawBitPattern(_bits) &<< 32 | _RawBitPattern(variantBits)
#else
return Builtin.reinterpretCast(_object)
#endif
}
}
@inlinable
@inline(__always)
// TODO: private
internal
init(taggedRawBits: _RawBitPattern) {
#if arch(i386) || arch(arm)
self.init(
Builtin.reinterpretCast(UInt(truncatingIfNeeded: taggedRawBits)),
UInt(truncatingIfNeeded: taggedRawBits &>> 32))
#else
self.init(_bridgeObject(fromTagged: taggedRawBits))
_sanityCheck(self.isValue)
#endif
}
@inlinable
@inline(__always)
// TODO: private
internal
init(nonTaggedRawBits: _RawBitPattern) {
#if arch(i386) || arch(arm)
self.init(
Builtin.reinterpretCast(UInt(truncatingIfNeeded: nonTaggedRawBits)),
UInt(truncatingIfNeeded: nonTaggedRawBits &>> 32))
#else
self.init(Builtin.reinterpretCast(nonTaggedRawBits))
_sanityCheck(!self.isValue)
#endif
}
// For when you need to hack around ARC. Note that by using this initializer,
// we are giving up on compile-time constant folding of ARC of values. Thus,
// this should only be called from the callee of a non-inlineable function
// that has no knowledge of the value-ness of the object.
@inlinable
@inline(__always)
// TODO: private
internal
init(noReallyHereAreTheRawBits bits: _RawBitPattern) {
#if arch(i386) || arch(arm)
self.init(
Builtin.reinterpretCast(UInt(truncatingIfNeeded: bits)),
UInt(truncatingIfNeeded: bits &>> 32))
#else
self.init(Builtin.reinterpretCast(bits))
#endif
}
}
// ## _StringObject bit layout
//
// x86-64 and arm64: (one 64-bit word)
// +---+---+---|---+------+----------------------------------------------------+
// + t | v | o | w | uuuu | payload (56 bits) |
// +---+---+---|---+------+----------------------------------------------------+
// msb lsb
//
// i386 and arm: (two 32-bit words)
// _variant _bits
// +------------------------------------+ +------------------------------------+
// + .strong(AnyObject) | | v | o | w | unused (29 bits) |
// +------------------------------------+ +------------------------------------+
// + .unmanaged{Single,Double}Byte | | start address (32 bits) |
// +------------------------------------+ +------------------------------------+
// + .small{Single,Double}Byte | | payload (32 bits) |
// +------------------------------------+ +------------------------------------+
// msb lsb msb lsb
//
// where t: is-a-value, i.e. a tag bit that says not to perform ARC
// v: sub-variant bit, i.e. set for isCocoa or isSmall
// o: is-opaque, i.e. opaque vs contiguously stored strings
// w: width indicator bit (0: ASCII, 1: UTF-16)
// u: unused bits
//
// payload is:
// isNative: the native StringStorage object
// isCocoa: the Cocoa object
// isOpaque & !isCocoa: the _OpaqueString object
// isUnmanaged: the pointer to code units
// isSmall: opaque bits used for inline storage // TODO: use them!
//
extension _StringObject {
#if arch(i386) || arch(arm)
@inlinable
internal
static var _isCocoaBit: UInt {
@inline(__always)
get {
return 0x8000_0000
}
}
@inlinable
internal
static var _isOpaqueBit: UInt {
@inline(__always)
get {
return 0x4000_0000
}
}
@inlinable
internal
static var _twoByteBit: UInt {
@inline(__always)
get {
return 0x2000_0000
}
}
#else // !(arch(i386) || arch(arm))
@inlinable
internal
static var _isValueBit: UInt {
@inline(__always)
get {
// NOTE: deviating from ObjC tagged pointer bits, as we just want to avoid
// swift runtime management, and top bit suffices for that.
return 0x80_00_0000_0000_0000
}
}
// After deciding isValue, which of the two variants (on both sides) are we.
// That is, native vs objc or unsafe vs small.
@inlinable
internal
static var _subVariantBit: UInt {
@inline(__always)
get {
return 0x40_00_0000_0000_0000
}
}
@inlinable
internal
static var _isOpaqueBit: UInt {
@inline(__always)
get {
return 0x20_00_0000_0000_0000
}
}
@inlinable
internal
static var _twoByteBit: UInt {
@inline(__always)
get {
return 0x10_00_0000_0000_0000
}
}
// There are 4 sub-variants depending on the isValue and subVariant bits
@inlinable
internal
static var _variantMask: UInt {
@inline(__always)
get { return _isValueBit | _subVariantBit }
}
@inlinable
internal
static var _payloadMask: UInt {
@inline(__always)
get {
return 0x00FF_FFFF_FFFF_FFFF
}
}
@inlinable
internal
var _variantBits: UInt {
@inline(__always)
get {
return rawBits & _StringObject._variantMask
}
}
#endif // arch(i386) || arch(arm)
@inlinable
internal
var referenceBits: UInt {
@inline(__always)
get {
#if arch(i386) || arch(arm)
guard case let .strong(object) = _variant else {
_sanityCheckFailure("internal error: expected a non-tagged String")
}
return Builtin.reinterpretCast(object)
#else
_sanityCheck(isNative || isCocoa)
return rawBits & _StringObject._payloadMask
#endif
}
}
@inlinable
internal
var payloadBits: UInt {
@inline(__always)
get {
#if arch(i386) || arch(arm)
if case .strong(_) = _variant {
_sanityCheckFailure("internal error: expected a tagged String")
}
return _bits
#else
_sanityCheck(!isNative && !isCocoa)
return rawBits & _StringObject._payloadMask
#endif
}
}
}
//
// Empty strings
//
#if arch(i386) || arch(arm)
internal var _emptyStringStorage: UInt32 = 0
// NB: This function *cannot* be @inlinable because it expects to project
// and escape the physical storage of `_emptyStringStorage`.
// Marking it inlinable will cause it to resiliently use accessors to
// project `_emptyStringStorage` as a computed
// property.
@usableFromInline // FIXME(sil-serialize-all)
internal var _emptyStringAddressBits: UInt {
let p = UnsafeRawPointer(Builtin.addressof(&_emptyStringStorage))
return UInt(bitPattern: p)
}
#endif // arch(i386) || arch(arm)
extension _StringObject {
#if arch(i386) || arch(arm)
@inlinable
internal
var isEmptySingleton: Bool {
guard _bits == _emptyStringAddressBits else { return false }
switch _variant {
case .unmanagedSingleByte, .unmanagedDoubleByte:
return true
default:
return false
}
}
@inlinable
@inline(__always)
internal
init() {
self.init(.unmanagedSingleByte, _emptyStringAddressBits)
}
#else
@inlinable
internal
static var _emptyStringBitPattern: UInt {
@inline(__always)
get { return _smallUTF8TopNibble }
}
@inlinable
internal
var isEmptySingleton: Bool {
@inline(__always)
get { return rawBits == _StringObject._emptyStringBitPattern }
}
@inlinable
@inline(__always)
internal
init() {
self.init(taggedRawBits: _StringObject._emptyStringBitPattern)
}
#endif
}
//
// Small strings
//
extension _StringObject {
// TODO: Decide what to do for the last bit in the top nibble, when we scrap
// the opaque bit (which should really be the isSmallUTF8String bit)
//
// TODO: Pretty ASCII art, better description
//
// An encoded small UTF-8 string's first byte has a leading nibble of 1110
// and a trailing nibble containing the count.
#if arch(i386) || arch(arm)
#else
@inlinable internal
static var _topNibbleMask: UInt {
@inline(__always)
get { return 0xF000_0000_0000_0000 }
}
@inlinable internal
static var _smallUTF8TopNibble: UInt {
@inline(__always)
get { return 0xE000_0000_0000_0000 }
}
@inlinable internal
static var _smallUTF8CountMask: UInt {
@inline(__always)
get { return 0x0F00_0000_0000_0000 }
}
#endif
@inlinable
internal
var _isSmallUTF8: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
return false
#else
return rawBits & _StringObject._topNibbleMask
== _StringObject._smallUTF8TopNibble
#endif
}
}
// TODO: describe better
//
// The top nibble is the mask, second nibble the count. Turn off the mask and
// keep the count. The StringObject represents the second word of a
// SmallUTF8String.
//
@inlinable
internal
var asSmallUTF8SecondWord: UInt {
@inline(__always)
get {
#if arch(i386) || arch(arm)
unsupportedOn32bit()
#else
_sanityCheck(_isSmallUTF8)
return rawBits & ~_StringObject._topNibbleMask
#endif
}
}
@inlinable
internal
var smallUTF8Count: Int {
@inline(__always)
get {
#if arch(i386) || arch(arm)
unsupportedOn32bit()
#else
_sanityCheck(_isSmallUTF8)
let count = (rawBits & _StringObject._smallUTF8CountMask) &>> 56
_sanityCheck(count <= _SmallUTF8String.capacity)
return Int(bitPattern: count)
#endif
}
}
@inlinable
internal
init(_smallUTF8SecondWord bits: UInt) {
#if arch(i386) || arch(arm)
unsupportedOn32bit()
#else
_sanityCheck(bits & _StringObject._topNibbleMask == 0)
self.init(taggedRawBits: bits | _StringObject._smallUTF8TopNibble)
#endif
}
}
//
// Private convenience helpers to layer on top of BridgeObject
//
// TODO: private!
//
extension _StringObject {
@inlinable
internal // TODO: private!
var asNativeObject: AnyObject {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(let object):
_sanityCheck(_bits & _StringObject._isCocoaBit == 0)
_sanityCheck(_usesNativeSwiftReferenceCounting(type(of: object)))
return object
default:
_sanityCheckFailure("asNativeObject on unmanaged _StringObject")
}
#else
_sanityCheck(isNative)
_sanityCheck(
_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(referenceBits) as AnyObject)))
return Builtin.reinterpretCast(referenceBits)
#endif
}
}
#if _runtime(_ObjC)
@inlinable
internal // TODO: private!
var asCocoaObject: _CocoaString {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(let object):
_sanityCheck(_bits & _StringObject._isCocoaBit != 0)
_sanityCheck(!_usesNativeSwiftReferenceCounting(type(of: object)))
return object
default:
_sanityCheckFailure("asCocoaObject on unmanaged _StringObject")
}
#else
_sanityCheck(isCocoa)
_sanityCheck(
!_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(referenceBits) as AnyObject)))
return Builtin.reinterpretCast(referenceBits)
#endif
}
}
#endif
@inlinable
internal // TODO: private!
var asOpaqueObject: _OpaqueString {
@inline(__always)
get {
_sanityCheck(isOpaque)
let object = Builtin.reinterpretCast(referenceBits) as AnyObject
return object as! _OpaqueString
}
}
@inlinable
internal
var asUnmanagedRawStart: UnsafeRawPointer {
@inline(__always)
get {
_sanityCheck(isUnmanaged)
#if arch(i386) || arch(arm)
return UnsafeRawPointer(bitPattern: _bits)._unsafelyUnwrappedUnchecked
#else
return UnsafeRawPointer(
bitPattern: payloadBits
)._unsafelyUnwrappedUnchecked
#endif
}
}
}
//
// Queries on a StringObject
//
extension _StringObject {
//
// Determine which of the 4 major variants we are
//
@inlinable
internal
var isNative: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
guard case .strong(_) = _variant else { return false }
return _bits & _StringObject._isCocoaBit == 0
#else
return _variantBits == 0
#endif
}
}
@inlinable
internal
var isCocoa: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
guard case .strong(_) = _variant else { return false }
return _bits & _StringObject._isCocoaBit != 0
#else
return _variantBits == _StringObject._subVariantBit
#endif
}
}
public // @testable
var owner: AnyObject? { // For testing only
#if arch(i386) || arch(arm)
guard case .strong(let object) = _variant else { return nil }
return object
#else
if _fastPath(isNative || isCocoa) {
return Builtin.reinterpretCast(referenceBits)
}
return nil
#endif
}
@inlinable
internal
var isValue: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(_): return false
default:
return true
}
#else
return rawBits & _StringObject._isValueBit != 0
#endif
}
}
@inlinable
internal
var isUnmanaged: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .unmanagedSingleByte, .unmanagedDoubleByte:
return true
default:
return false
}
#else
return _variantBits == _StringObject._isValueBit
#endif
}
}
@inlinable
internal
var isSmall: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .smallSingleByte, .smallDoubleByte:
return true
default:
return false
}
#else
return _variantBits == _StringObject._variantMask
#endif
}
}
@inlinable
internal
var isSmallOrCocoa: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .smallSingleByte, .smallDoubleByte:
return true
default:
return isCocoa
}
#else
return rawBits & _StringObject._subVariantBit != 0
#endif
}
}
//
// Frequently queried properties
//
@inlinable
internal
var isContiguous: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(_):
return _bits & _StringObject._isOpaqueBit == 0
case .unmanagedSingleByte, .unmanagedDoubleByte:
return true
case .smallSingleByte, .smallDoubleByte:
return false
}
#else
return rawBits & _StringObject._isOpaqueBit == 0
#endif
}
}
@inlinable
internal
var isOpaque: Bool {
@inline(__always)
get { return !isContiguous }
}
@inlinable
internal
var isContiguousCocoa: Bool {
@inline(__always)
get { return isContiguous && isCocoa }
}
@inlinable
internal
var isNoncontiguousCocoa: Bool {
@inline(__always)
get { return isCocoa && isOpaque }
}
@inlinable
var isSingleByte: Bool {
@inline(__always)
get {
#if arch(i386) || arch(arm)
switch _variant {
case .strong(_):
return _bits & _StringObject._twoByteBit == 0
case .unmanagedSingleByte, .smallSingleByte:
return true
case .unmanagedDoubleByte, .smallDoubleByte:
return false
}
#else
return rawBits & _StringObject._twoByteBit == 0
#endif
}
}
@inlinable
var byteWidth: Int {
@inline(__always)
get { return isSingleByte ? 1 : 2 }
}
@inlinable
var bitWidth: Int {
@inline(__always)
get { return byteWidth &<< 3 }
}
@inlinable
var isContiguousASCII: Bool {
@inline(__always)
get { return isContiguous && isSingleByte }
}
@inlinable
var isContiguousUTF16: Bool {
@inline(__always)
get { return isContiguous && !isSingleByte }
}
@inlinable
@inline(__always)
internal
func nativeStorage<CodeUnit>(
of codeUnit: CodeUnit.Type = CodeUnit.self
) -> _SwiftStringStorage<CodeUnit>
where CodeUnit : FixedWidthInteger & UnsignedInteger {
_sanityCheck(isNative)
_sanityCheck(CodeUnit.bitWidth == self.bitWidth)
// TODO: Is this the way to do it?
return _unsafeUncheckedDowncast(
asNativeObject, to: _SwiftStringStorage<CodeUnit>.self)
}
@inlinable
var nativeRawStorage: _SwiftRawStringStorage {
@inline(__always) get {
_sanityCheck(isNative)
return _unsafeUncheckedDowncast(
asNativeObject, to: _SwiftRawStringStorage.self)
}
}
}
extension _StringObject {
@inlinable // FIXME(sil-serialize-all)
internal func _invariantCheck() {
#if INTERNAL_CHECKS_ENABLED
_sanityCheck(MemoryLayout<_StringObject>.size == 8)
_sanityCheck(isContiguous || isOpaque)
_sanityCheck(isOpaque || isContiguousASCII || isContiguousUTF16)
if isNative {
_sanityCheck(isContiguous)
if isSingleByte {
_sanityCheck(isContiguousASCII)
_sanityCheck(asNativeObject is _SwiftStringStorage<UInt8>)
} else {
_sanityCheck(asNativeObject is _SwiftStringStorage<UInt16>)
}
} else if isUnmanaged {
_sanityCheck(isContiguous)
_sanityCheck(payloadBits > 0) // TODO: inside address space
} else if isCocoa {
#if _runtime(_ObjC)
let object = asCocoaObject
_sanityCheck(
!_usesNativeSwiftReferenceCounting(type(of: object as AnyObject)))
#else
_sanityCheckFailure("Cocoa objects aren't supported on this platform")
#endif
} else if isSmall {
// TODO: Drop the whole opaque bit thing...
_sanityCheck(isOpaque)
} else {
fatalError("Unimplemented string form")
}
#endif // INTERNAL_CHECKS_ENABLED
}
}
//
// Conveniently construct, tag, flag, etc. StringObjects
//
extension _StringObject {
@inlinable
@inline(__always)
internal
init(
_payloadBits: UInt,
isValue: Bool,
isSmallOrObjC: Bool,
isOpaque: Bool,
isTwoByte: Bool
) {
#if INTERNAL_CHECKS_ENABLED
defer {
_sanityCheck(isSmall == (isValue && isSmallOrObjC))
_sanityCheck(isUnmanaged == (isValue && !isSmallOrObjC))
_sanityCheck(isCocoa == (!isValue && isSmallOrObjC))
_sanityCheck(isNative == (!isValue && !isSmallOrObjC))
}
#endif
#if arch(i386) || arch(arm)
if isValue {
if isSmallOrObjC {
_sanityCheck(isOpaque)
self.init(isTwoByte ? .smallDoubleByte : .smallSingleByte, _payloadBits)
} else {
_sanityCheck(!isOpaque)
self.init(
isTwoByte ? .unmanagedDoubleByte : .unmanagedSingleByte, _payloadBits)
}
return
}
var bits: UInt = 0
if isSmallOrObjC {
bits |= _StringObject._isCocoaBit
}
if isOpaque {
bits |= _StringObject._isOpaqueBit
}
if isTwoByte {
bits |= _StringObject._twoByteBit
}
self.init(.strong(Builtin.reinterpretCast(_payloadBits)), bits)
#else
_sanityCheck(_payloadBits & ~_StringObject._payloadMask == 0)
var rawBits = _payloadBits
if isValue {
var rawBitsBuiltin = Builtin.stringObjectOr_Int64(
rawBits._value, _StringObject._isValueBit._value)
if isSmallOrObjC {
rawBitsBuiltin = Builtin.stringObjectOr_Int64(
rawBitsBuiltin, _StringObject._subVariantBit._value)
}
if isOpaque {
rawBitsBuiltin = Builtin.stringObjectOr_Int64(
rawBitsBuiltin, _StringObject._isOpaqueBit._value)
}
if isTwoByte {
rawBitsBuiltin = Builtin.stringObjectOr_Int64(
rawBitsBuiltin, _StringObject._twoByteBit._value)
}
rawBits = UInt(rawBitsBuiltin)
self.init(taggedRawBits: rawBits)
} else {
if isSmallOrObjC {
rawBits |= _StringObject._subVariantBit
}
if isOpaque {
rawBits |= _StringObject._isOpaqueBit
}
if isTwoByte {
rawBits |= _StringObject._twoByteBit
}
self.init(nonTaggedRawBits: rawBits)
}
#endif
}
@inlinable
@inline(__always)
internal
init(
_someObject: AnyObject,
isCocoa: Bool,
isContiguous: Bool,
isSingleByte: Bool
) {
defer { _fixLifetime(_someObject) }
self.init(
_payloadBits: Builtin.reinterpretCast(_someObject),
isValue: false,
isSmallOrObjC: isCocoa,
isOpaque: !isContiguous,
isTwoByte: !isSingleByte)
}
@inlinable
@inline(__always)
internal
init(nativeObject: AnyObject, isSingleByte: Bool) {
self.init(
_someObject: nativeObject,
isCocoa: false,
isContiguous: true,
isSingleByte: isSingleByte)
}
#if _runtime(_ObjC)
@inlinable
@inline(__always)
internal
init(cocoaObject: AnyObject, isSingleByte: Bool, isContiguous: Bool) {
// TODO: is it possible to sanity check? maybe `is NSObject`?
self.init(
_someObject: cocoaObject,
isCocoa: true,
isContiguous: isContiguous,
isSingleByte: isSingleByte)
}
#else
@inlinable
@inline(__always)
internal
init<S: _OpaqueString>(opaqueString: S) {
self.init(
_someObject: opaqueString,
isCocoa: false,
isContiguous: false,
isSingleByte: false)
}
#endif
@inlinable
@inline(__always)
internal
init<CodeUnit>(
unmanaged: UnsafePointer<CodeUnit>
) where CodeUnit : FixedWidthInteger & UnsignedInteger {
self.init(
_payloadBits: UInt(bitPattern: unmanaged),
isValue: true,
isSmallOrObjC: false,
isOpaque: false,
isTwoByte: CodeUnit.bitWidth == 16)
_sanityCheck(isSingleByte == (CodeUnit.bitWidth == 8))
}
@inlinable
@inline(__always)
internal
init<CodeUnit>(
_ storage: _SwiftStringStorage<CodeUnit>
) where CodeUnit : FixedWidthInteger & UnsignedInteger {
self.init(nativeObject: storage, isSingleByte: CodeUnit.bitWidth == 8)
_sanityCheck(isSingleByte == (CodeUnit.bitWidth == 8))
}
}
|
apache-2.0
|
05419fad7beb35b96fa51b39995b4cff
| 23.781314 | 80 | 0.630194 | 4.040341 | false | false | false | false |
Skyscanner/SkyFloatingLabelTextField
|
SkyFloatingLabelTextField/SkyFloatingLabelTextFieldExample/Example5/DelegateMethodsViewController.swift
|
1
|
3586
|
// Copyright 2016-2019 Skyscanner Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
import UIKit
class DelegateMethodsViewController: UIViewController, UITextFieldDelegate {
@IBOutlet var textField: SkyFloatingLabelTextField?
@IBOutlet var logTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
textField?.delegate = self
logTextView?.text = ""
}
@IBOutlet var addErrorButton: UIButton?
@IBAction func addError() {
let localizedAddError = NSLocalizedString(
"Add error",
tableName: "SkyFloatingLabelTextField",
comment: "add error button title"
)
if addErrorButton?.title(for: .normal) == localizedAddError {
textField?.errorMessage = NSLocalizedString(
"error message",
tableName: "SkyFloatingLabelTextField",
comment: "error message"
)
addErrorButton?.setTitle(
NSLocalizedString(
"Clear error",
tableName: "SkyFloatingLabelTextField",
comment: "clear errors button title"
),
for: .normal
)
} else {
textField?.errorMessage = ""
addErrorButton?.setTitle(
NSLocalizedString(
"Add error",
tableName: "SkyFloatingLabelTextField",
comment: "add error button title"
),
for: .normal
)
}
}
@IBAction func resignTextField() {
self.textField?.resignFirstResponder()
}
func log(text: String) {
let date = NSDate()
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
let row = "\(formatter.string(from: date as Date)) : \(text)"
logTextView.text = "\(row)\n" + logTextView.text!
}
// MARK: - SkyFloatingLabelTextField delegate
func textFieldDidBeginEditing(_ textField: UITextField) {
log(text: "textFieldDidBeginEditing:")
}
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
log(text: "textField:shouldChangeCharactersInRange:replacementString:")
return true
}
func textFieldDidEndEditing(_ textField: UITextField) {
log(text: "textFieldDidEndEditing:")
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
log(text: "textFieldShouldBeginEditing:")
return true
}
func textFieldShouldClear(_ textField: UITextField) -> Bool {
log(text: "textFieldShouldClear:")
return true
}
func textFieldShouldEndEditing(_ textField: UITextField) -> Bool {
log(text: "textFieldShouldEndEditing:")
return true
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
log(text: "textFieldShouldReturn")
return true
}
}
|
apache-2.0
|
3ad189ea52a84272d833c21bd5e784fa
| 30.734513 | 94 | 0.611266 | 5.273529 | false | false | false | false |
peterobbin/atomSimulation
|
atoms/Electron.swift
|
1
|
1470
|
//
// Electron.swift
// atoms
//
// Created by Luobin Wang on 7/31/15.
// Copyright © 2015 Luobin Wang. All rights reserved.
//
import Foundation
import SpriteKit
class Electron {
let etron = SKSpriteNode(imageNamed: "electron")
var pos = CGPointZero
var osciScale = CGFloat()
var timeOffset = CGFloat()
var orbitSpeed = CGFloat()
var clockWise = Bool()
func setup(_pos:CGPoint, _osciScale:CGFloat){
self.pos = _pos
self.osciScale = _osciScale
let decideOrbitOrient = random(0, max: 1)
if decideOrbitOrient > 0.5 {
clockWise = true
}else{
clockWise = false
}
timeOffset = CGFloat(random(0, max: CGFloat(M_PI * 2)))
orbitSpeed = CGFloat(random(0, max: 10))
etron.name = "electron"
etron.position = pos
}
func update(){
let time = CGFloat(CFAbsoluteTimeGetCurrent()) * orbitSpeed + timeOffset
let xOsci = CGFloat(sin(time)) * osciScale
let yOsci = CGFloat(cos(time)) * osciScale
if clockWise {
etron.position = CGPoint(x: pos.x + xOsci, y: pos.y + yOsci)
}else{
etron.position = CGPoint(x: pos.x + yOsci, y: pos.y + xOsci)
}
}
func random() ->CGFloat{
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(min: CGFloat, max: CGFloat) ->CGFloat{
return random() * (max - min) + min
}
}
|
mit
|
6e1bbe38a6560478454a194b045f1af3
| 26.735849 | 80 | 0.575902 | 3.636139 | false | false | false | false |
saragiotto/TMDbFramework
|
Example/Pods/Nimble/Sources/Nimble/Matchers/BeGreaterThan.swift
|
2
|
1731
|
import Foundation
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan<T: Comparable>(_ expectedValue: T?) -> Predicate<T> {
let errorMessage = "be greater than <\(stringify(expectedValue))>"
return Predicate.simple(errorMessage) { actualExpression in
if let actual = try actualExpression.evaluate(), let expected = expectedValue {
return PredicateStatus(bool: actual > expected)
}
return .fail
}
}
/// A Nimble matcher that succeeds when the actual value is greater than the expected value.
public func beGreaterThan(_ expectedValue: NMBComparable?) -> Predicate<NMBComparable> {
let errorMessage = "be greater than <\(stringify(expectedValue))>"
return Predicate.simple(errorMessage) { actualExpression in
let actualValue = try actualExpression.evaluate()
let matches = actualValue != nil
&& actualValue!.NMB_compare(expectedValue) == ComparisonResult.orderedDescending
return PredicateStatus(bool: matches)
}
}
public func ><T: Comparable>(lhs: Expectation<T>, rhs: T) {
lhs.to(beGreaterThan(rhs))
}
public func > (lhs: Expectation<NMBComparable>, rhs: NMBComparable?) {
lhs.to(beGreaterThan(rhs))
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
extension NMBObjCMatcher {
@objc public class func beGreaterThanMatcher(_ expected: NMBComparable?) -> NMBObjCMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let expr = actualExpression.cast { $0 as? NMBComparable }
return try! beGreaterThan(expected).matches(expr, failureMessage: failureMessage)
}
}
}
#endif
|
mit
|
795a8311cefae39e841419824a7c5b65
| 40.214286 | 96 | 0.701329 | 4.86236 | false | false | false | false |
iOS-mamu/SS
|
P/Potatso/Advance/RuleConfigurationViewController.swift
|
1
|
4060
|
//
// RuleConfigurationViewController.swift
// Potatso
//
// Created by LEI on 3/9/16.
// Copyright © 2016 TouchingApp. All rights reserved.
//
import UIKit
import Eureka
import PotatsoLibrary
import PotatsoModel
import RealmSwift
private let kRuleFormType = "type"
private let kRuleFormValue = "value"
private let kRuleFormAction = "action"
extension Rule {
var rowDescription: (String?, String?) {
return (action.rawValue, "\(type.rawValue)(\(value))")
}
}
class RuleConfigurationViewController: FormViewController {
var rule: Rule
var callback: ((Rule) -> Void)?
var editable: Bool = true
let isEdit: Bool
init(rule: Rule?, callback: ((Rule) -> Void)?) {
if let rule = rule {
self.rule = rule
isEdit = true
}else {
self.rule = Rule(type: RuleType.DomainSuffix, action: RuleAction.Proxy, value: "")
isEdit = false
}
self.callback = callback
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
if editable {
if isEdit {
self.navigationItem.title = "Edit Rule".localized()
}else {
self.navigationItem.title = "Add Rule".localized()
}
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(save))
}else {
navigationItem.title = "Rule".localized()
}
generateForm()
}
func generateForm() {
form +++ Section()
<<< PushRow<RuleType>(kRuleFormType) {
$0.title = "Type".localized()
$0.selectorTitle = "Choose type of rule".localized()
$0.options = [RuleType.DomainSuffix, RuleType.DomainMatch, RuleType.Domain, RuleType.IPCIDR, RuleType.GeoIP]
$0.value = self.rule.type
$0.disabled = Condition(booleanLiteral: !editable)
}.cellSetup({ (cell, row) -> () in
cell.accessoryType = .disclosureIndicator
})
<<< TextRow(kRuleFormValue) {
$0.title = "Value".localized()
$0.value = self.rule.value
$0.disabled = Condition(booleanLiteral: !editable)
}.cellSetup({ (cell, row) -> () in
cell.textField.keyboardType = .URL
cell.textField.autocorrectionType = .no
cell.textField.autocapitalizationType = .none
})
<<< PushRow<RuleAction>(kRuleFormAction) {
$0.title = "Action".localized()
$0.selectorTitle = "Choose action for rule".localized()
$0.options = [RuleAction.Proxy, RuleAction.Direct, RuleAction.Reject]
$0.value = self.rule.action
$0.disabled = Condition(booleanLiteral: !editable)
}.cellSetup({ (cell, row) -> () in
cell.accessoryType = .disclosureIndicator
})
}
func save() {
do {
let values = form.values()
guard let type = values[kRuleFormType] as? RuleType else {
throw "You must choose a type".localized()
}
guard let value = (values[kRuleFormValue] as? String)?.trimmingCharacters(in: CharacterSet.whitespaces), value.characters.count > 0 else {
throw "Value can't be empty".localized()
}
guard let action = values[kRuleFormAction] as? RuleAction else {
throw "You must choose a action".localized()
}
rule.type = type
rule.value = value
rule.action = action
callback?(rule)
close()
}catch {
showTextHUD("\(error)", dismissAfterDelay: 1.0)
}
}
}
|
mit
|
e8c9ad7420af6d40ed4c6ad1e4db2995
| 33.109244 | 150 | 0.549643 | 4.714286 | false | false | false | false |
KBryan/SwiftFoundation
|
Source/URL.swift
|
1
|
4379
|
//
// URL.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 6/29/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
/// Encapsulates the components of an URL.
public struct URL: CustomStringConvertible {
// MARK: - Properties
public var scheme: String
public var user: String?
public var password: String?
/// The host URL subcomponent (e.g. domain name, IP address)
public var host: String?
public var port: UInt?
public var path: String?
public var query: [(String, String)]?
/// The fragment URL component (the part after a # symbol)
public var fragment: String?
// MARK: - Initialization
public init(scheme: String) {
self.scheme = scheme
}
/// Creates an instance from the string. String must be a valid URL.
public init?(stringValue: String) {
// parse string
return nil
}
// MARK: - Generated Properties
/// Whether the URL components form a valid URL
public var valid: Bool {
// validate scheme
// host must exist for port to be specified
guard !(host != nil && port == nil) else { return false }
// user and password must both be nil or non-nil
guard !((user != nil || password != nil) && (user == nil || password == nil)) else { return false }
// query must have at least one item
if query != nil { guard query!.count > 0 else { return false } }
return true
}
/// Returns a valid URL string or ```nil```
public var URLString: String? {
guard self.valid else { return nil }
var stringValue = scheme + "://"
if let user = user { stringValue += user }
if let password = password { stringValue += ":\(password)"}
if user != nil { stringValue += "@" }
if let host = host { stringValue += host }
if let port = port { stringValue += ":\(port)" }
if let path = path { stringValue += "/\(path)" }
if let query = query {
stringValue += "?"
for (index, queryItem) in query.enumerate() {
let (name, value) = queryItem
stringValue += name + "=" + value
if index != query.count - 1 {
stringValue += "&"
}
}
}
if let fragment = fragment { stringValue += "#\(fragment)" }
return stringValue
}
public var description: String {
let separator = " "
var description = ""
if let URLString = URLString {
description += "URL: " + URLString + separator
}
description += "Scheme: " + scheme
if let user = user {
description += separator + "User: " + user
}
if let password = password {
description += separator + "Password: " + password
}
if let host = host {
description += separator + "Host: " + host
}
if let port = port {
description += separator + "Port: " + "\(port)"
}
if let path = path {
description += separator + "Path: " + path
}
if let query = query {
var stringValue = ""
for (index, queryItem) in query.enumerate() {
let (name, value) = queryItem
stringValue += name + "=" + value
if index != query.count - 1 {
stringValue += "&"
}
}
description += separator + "Query: " + stringValue
}
if let fragment = fragment {
description += separator + "Fragment: " + fragment
}
return description
}
}
|
mit
|
450330fdcc5eaf292087d8bb13e834bf
| 24.306358 | 107 | 0.448378 | 5.67834 | false | false | false | false |
TsuiOS/LoveFreshBeen
|
LoveFreshBeenX/Class/Model/XNFreshHot.swift
|
1
|
1753
|
//
// XNFreshHot.swift
// LoveFreshBeenX
//
// Created by xuning on 16/6/22.
// Copyright © 2016年 hus. All rights reserved.
//
import UIKit
class XNFreshHot: Reflect {
var page: Int = -1
var code: Int = -1
var msg: String?
var data: [XNGoods]?
class func loadFreshHotData(completion:(data: XNFreshHot?, error: NSError?) -> Void) {
let path = NSBundle.mainBundle().pathForResource("首页新鲜热卖", ofType: nil)
let data = NSData(contentsOfFile: path!)
if data != nil {
let dict: NSDictionary = (try! NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)) as! NSDictionary
let data = XNFreshHot.parse(dict: dict)
completion(data: data, error: nil)
}
}
}
class XNGoods: Reflect{
//*************************商品模型默认属性**********************************
/// 商品ID
var id: String?
/// 商品姓名
var name: String?
var brand_id: String?
/// 超市价格
var market_price: String?
var cid: String?
var category_id: String?
/// 当前价格
var partner_price: String?
var brand_name: String?
var pre_img: String?
var pre_imgs: String?
/// 参数
var specifics: String?
var product_id: String?
var dealer_id: String?
/// 当前价格
var price: String?
/// 库存
var number: Int = -1
/// 买一赠一
var pm_desc: String?
/// urlStr
var img: String?
/// 是不是精选 0 : 不是, 1 : 是
var is_xf: Int = 0
//*************************商品模型辅助属性**********************************
// 记录用户对商品添加次数
var userBuyNumber: Int = 0
}
|
mit
|
8a5e783722c882cc8c4ad88eff4535ad
| 23.134328 | 132 | 0.537748 | 3.647856 | false | false | false | false |
someoneAnyone/Nightscouter
|
Common/Views/CompassControl+Convience.swift
|
1
|
1322
|
//
// CompassControl+Convience.swift
// Nightscouter
//
// Created by Peter Ina on 6/30/15.
// Copyright (c) 2015 Peter Ina. All rights reserved.
//
import UIKit
public extension CompassControl {
func configure(_ sgvText: String, color: UIColor, direction: Direction, bgdelta: String, units: String) -> Void {
self.sgvText = sgvText
self.color = color
self.direction = direction
self.delta = bgdelta//bgdelta.formattedBGDelta(forUnits: GlucoseUnit(rawValue: units))//"\(bgdelta.formattedForBGDelta) \(units)"
}
func configure(withDataSource dataSource: CompassViewDataSource, delegate: CompassViewDelegate?) {
direction = dataSource.direction
delta = dataSource.detailText
sgvText = dataSource.text
color = delegate?.desiredColor.colorValue ?? DesiredColorState.neutral.colorValue
shouldLookStale(look: dataSource.lookStale)
}
@objc func shouldLookStale(look stale: Bool = true) {
if stale {
let compass = CompassControl()
self.alpha = 0.5
self.color = compass.color
self.sgvText = compass.sgvText
self.direction = compass.direction
self.delta = compass.delta
} else {
self.alpha = 1.0
}
}
}
|
mit
|
3b9e0d9594499f7b1bcfe921233053e8
| 31.243902 | 137 | 0.636914 | 4.196825 | false | false | false | false |
gmission/gmission-ios
|
gmission/gmission/MapVC.swift
|
1
|
6339
|
//
// MapVC.swift
// gmission
//
// Created by CHEN Zhao on 4/12/2015.
// Copyright © 2015 CHEN Zhao. All rights reserved.
//
import UIKit
import GoogleMaps
class MapVM{
let hits = ArrayForTableView<Hit>()
init(){
}
func refresh(done:F = nil){
self.hits.removeAll()
let q = [ "filters" : [ ["name":"campaign_id","op":"is_null","val":"null"], ["name":"location_id","op":"is_not_null","val":"null"] ], "limit":100, "order_by":[ ["field":"created_on", "direction":"desc"] ] ]
Hit.query(q){ (hits:[Hit])->Void in
self.hits.appendContentsOf(hits)
done?()
}
}
var currentLocation:CLLocation! = nil
var currentLocationName:String = "Earth"
}
private var myContext = 0
class MapVC: EnhancedVC, GMSMapViewDelegate {
var vm = MapVM()
@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Map"
self.navigationItem.setRightBarButtonItem(UIBarButtonItem(title: "HIT List", style: UIBarButtonItemStyle.Plain, target: self, action: "gotoHitList"), animated: true)
// Do any additional setup after loading the view.
self.mapView.myLocationEnabled = true
initMapWithFireBird()
}
override func viewWillAppear(animated: Bool) {
vm.refresh { () -> Void in
self.addHitsToMap()
}
super.viewWillAppear(animated)
}
func initMapWithFireBird(){
let camera = GMSCameraPosition.cameraWithLatitude(22.337522, longitude: 114.262969, zoom: 15)
mapView.camera = camera;
mapView.myLocationEnabled = true
mapView.delegate = self;
mapView.settings.myLocationButton = true
mapView.settings.rotateGestures = false
mapView.addObserver(self, forKeyPath: "myLocation", options: .New, context: &myContext)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
print("observed")
if context == &myContext {
if let newValue = change?[NSKeyValueChangeNewKey] {
if let location:CLLocation = newValue as? CLLocation{
print("got location")
self.vm.currentLocation = location
LocationManager.global.currentLoc = location
LocationManager.global.getCurrentLocationName({ (name:String) -> () in
self.vm.currentLocationName = name
self.title = name
})
}
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
func addHitsToMap(){
self.mapView.clear()
for hit in self.vm.hits.array{
hit.refreshLocation{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.addHitToMap(hit)
})
}
}
}
func addHitToMap(hit:Hit){
// println("add task \(task.location.lon) \(task.location.lat)")
let position = CLLocationCoordinate2DMake(hit.location!.lat, hit.location!.lon)
let marker = GMSMarker(position: position)
let uid = UserManager.currentUser?.id
let icon = UIImage(named: hit.requester_id == uid ? "HitMarkerOwn" : "HitMarker")
marker.icon = icon
marker.userData = hit
marker.snippet = hit.description
marker.title = hit.title
marker.map = self.mapView
}
func mapView(mapView: GMSMapView!, didTapInfoWindowOfMarker marker: GMSMarker!) {
let hit = marker.userData as! Hit
pushHitView(hit)
}
func mapView(mapView: GMSMapView!, didLongPressAtCoordinate coordinate: CLLocationCoordinate2D) {
print("try to ask location")
let marker = GMSMarker(position: coordinate)
marker.icon = UIImage(named: "HitMarkerOwn")
marker.map = self.mapView
self.showHUD("Loading..")
LocationManager.global.getLocationNameByCoord(coordinate, callback: { (var name) -> () in
print("ask location \(name)")
if name == "" {
name = "Unknown place"
}
self.askAboutLocation(name, coord: coordinate, onCancel: {()->() in
marker.map = nil
})
self.hideHUD()
// }else{
// self.flashHUD("Cannot get any info about this locaiton!", 1)
// dispatch_async(dispatch_get_main_queue() , { () -> Void in marker.map = nil })
// }
// }) { () -> () in
// self.flashHUD("Cannot get any info about this locaiton!", 1)
// dispatch_async(dispatch_get_main_queue() , { () -> Void in marker.map = nil })
})
}
func askAboutLocation(name:String, coord:CLLocationCoordinate2D, onCancel:(()->())? = nil){
let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let vc : AskVC = mainStoryboard.instantiateViewControllerWithIdentifier("AskVC") as! AskVC
vc.locName = name
vc.clLoc = CLLocation(latitude: coord.latitude, longitude: coord.longitude)
self.navigationController?.pushViewController(vc, animated: true)
}
func gotoHitList(){
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let hitListVC = storyboard.instantiateViewControllerWithIdentifier("hitListVC") as! HitListVC
self.navigationController?.pushViewController(hitListVC, animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
dc6260c4b50a906a0210f0dcbaf95ead
| 34.211111 | 216 | 0.594509 | 4.674041 | false | false | false | false |
cdesai/countmein
|
CountMeIn/AppDelegate.swift
|
1
|
3337
|
//
// AppDelegate.swift
// CountMeIn
//
// Created by Chinmay Desai on 29/09/2016.
// Copyright © 2016 Chinmay Desai. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
|
mit
|
b1fc910f8954337af5fcc8b956d90984
| 53.688525 | 285 | 0.765288 | 6.166359 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/Swiftz/Sources/Swiftz/DictionaryExt.swift
|
3
|
9786
|
//
// DictionaryExt.swift
// Swiftz
//
// Created by Maxwell Swadling on 5/06/2014.
// Copyright (c) 2014 Maxwell Swadling. All rights reserved.
//
extension Dictionary {
/// Initialize a Dictionary from a list of Key-Value pairs.
public init<S : Sequence>(_ seq : S)
where S.Iterator.Element == Element
{
self.init()
for (k, v) in seq {
self[k] = v
}
}
/// MARK: Query
/// Returns whether the given key exists in the receiver.
public func isMember(_ k : Key) -> Bool {
return self[k] != nil
}
/// Returns whether the given key does not exist in the receiver.
public func notMember(_ k : Key) -> Bool {
return !self.isMember(k)
}
/// Looks up a value in the receiver. If one is not found the default is
/// used.
public func lookup(_ k : Key, def : Value) -> Value {
return self[k] ?? def
}
/// Returns a copy of the receiver with the given key associated with the
/// given value.
public func insert(_ k : Key, v : Value) -> [Key: Value] {
var d = self
d[k] = v
return d
}
/// Returns a copy of the receiver with the given key associated with the
/// value returned from a combining function. If the receiver does not
/// contain a value for the given key this function is equivalent to an
/// `insert`.
public func insertWith(_ k : Key, v : Value, combiner : (Value) -> (Value) -> Value) -> [Key: Value] {
return self.insertWithKey(k, v: v, combiner: { (_ : Key, newValue : Value, oldValue : Value) -> Value in
return combiner(newValue)(oldValue)
})
}
/// Returns a copy of the receiver with the given key associated with the
/// value returned from a combining function. If the receiver does not
/// contain a value for the given key this function is equivalent to an
/// `insert`.
public func insertWith(_ k : Key, v : Value, combiner : @escaping (_ new : Value, _ old : Value) -> Value) -> [Key: Value] {
return self.insertWith(k, v: v, combiner: curry(combiner))
}
/// Returns a copy of the receiver with the given key associated with the
/// value returned from a combining function. If the receiver does not
/// contain a value for the given key this function is equivalent to an
/// `insert`.
public func insertWithKey(_ k : Key, v : Value, combiner : (Key) -> (Value) -> (Value) -> Value) -> [Key: Value] {
if let oldV = self[k] {
return self.insert(k, v: combiner(k)(v)(oldV))
}
return self.insert(k, v: v)
}
/// Returns a copy of the receiver with the given key associated with the
/// value returned from a combining function. If the receiver does not
/// contain a value for the given key this function is equivalent to an
/// `insert`.
public func insertWithKey(_ k : Key, v : Value, combiner : (_ key : Key, _ newValue : Value, _ oldValue : Value) -> Value) -> [Key: Value] {
if let oldV = self[k] {
return self.insert(k, v: combiner(k, v, oldV))
}
return self.insert(k, v: v)
}
/// Combines insert and retrieval of the old value if it exists.
public func insertLookupWithKey(_ k : Key, v : Value, combiner : (_ key : Key, _ newValue : Value, _ oldValue : Value) -> Value) -> (Optional<Value>, [Key: Value]) {
return (self[k], self.insertWithKey(k, v: v, combiner: combiner))
}
/// MARK: Update
/// Returns a copy of the receiver with the value for the given key removed.
public func delete(_ k : Key) -> [Key: Value] {
var d = self
d[k] = nil
return d
}
/// Updates a value at the given key with the result of the function
/// provided. If the key is not in the receiver this function is equivalent
/// to `identity`.
public func adjust(_ k : Key, adjustment : @escaping (Value) -> Value) -> [Key: Value] {
return self.adjustWithKey(k, adjustment: { (_, x) -> Value in
return adjustment(x)
})
}
/// Updates a value at the given key with the result of the function
/// provided. If the key is not in the receiver this function is equivalent
/// to `identity`.
public func adjustWithKey(_ k : Key, adjustment : @escaping (Key) -> (Value) -> Value) -> [Key: Value] {
return self.updateWithKey(k, update: { (k, x) -> Optional<Value> in
return .some(adjustment(k)(x))
})
}
/// Updates a value at the given key with the result of the function
/// provided. If the key is not in the receiver this function is equivalent
/// to `identity`.
public func adjustWithKey(_ k : Key, adjustment : @escaping (Key, Value) -> Value) -> [Key: Value] {
return self.adjustWithKey(k, adjustment: curry(adjustment))
}
/// Updates a value at the given key with the result of the function
/// provided. If the result of the function is `.none`, the value
/// associated with the given key is removed. If the key is not in the
/// receiver this function is equivalent to `identity`.
public func update(_ k : Key, update : @escaping (Value) -> Optional<Value>) -> [Key: Value] {
return self.updateWithKey(k, update: { (_, x) -> Optional<Value> in
return update(x)
})
}
/// Updates a value at the given key with the result of the function
/// provided. If the result of the function is `.none`, the value
/// associated with the given key is removed. If the key is not in the
/// receiver this function is equivalent to `identity`.
public func updateWithKey(_ k : Key, update : (Key) -> (Value) -> Optional<Value>) -> [Key: Value] {
if let oldV = self[k], let newV = update(k)(oldV) {
return self.insert(k, v: newV)
}
return self.delete(k)
}
/// Updates a value at the given key with the result of the function
/// provided. If the result of the function is `.none`, the value
/// associated with the given key is removed. If the key is not in the
/// receiver this function is equivalent to `identity`.
public func updateWithKey(_ k : Key, update : @escaping (Key, Value) -> Optional<Value>) -> [Key: Value] {
return self.updateWithKey(k, update: curry(update))
}
/// Alters the value (if any) for a given key with the result of the
/// function provided. If the result of the function is `.none`, the value
/// associated with the given key is removed.
public func alter(_ k : Key, alteration : (Optional<Value>) -> Optional<Value>) -> [Key: Value] {
if let newV = alteration(self[k]) {
return self.insert(k, v: newV)
}
return self.delete(k)
}
/// MARK: Map
/// Maps a function over all values in the receiver.
public func map<Value2>(_ f : @escaping (Value) -> Value2) -> [Key: Value2] {
return self.mapWithKey { (_, x) -> Value2 in
return f(x)
}
}
/// Maps a function over all keys and values in the receiver.
public func mapWithKey<Value2>(_ f : (Key) -> (Value) -> Value2) -> [Key: Value2] {
var d = [Key: Value2]()
self.forEach {
let (k, v) = $0
d[k] = f(k)(v)
}
return d
}
/// Maps a function over all keys and values in the receiver.
public func mapWithKey<Value2>(_ f : @escaping (Key, Value) -> Value2) -> [Key: Value2] {
return self.mapWithKey(curry(f))
}
/// Maps a function over all keys in the receiver.
public func mapKeys<Key2>(_ f : (Key) -> Key2) -> [Key2: Value] {
var d = [Key2: Value]()
self.forEach {
let (k, v) = $0
d[f(k)] = v
}
return d
}
/// Map values and collect the '.Some' results.
public func mapMaybe<Value2>(_ f : @escaping (Value) -> Value2?) -> [Key : Value2] {
return self.mapMaybeWithKey { (_, x) -> Value2? in
return f(x)
}
}
/// Map a function over all keys and values and collect the '.Some' results.
public func mapMaybeWithKey<B>(_ f : @escaping (Key, Value) -> B?) -> [Key : B] {
return self.mapMaybeWithKey(curry(f))
}
/// Map a function over all keys and values and collect the '.Some' results.
public func mapMaybeWithKey<B>(_ f : (Key) -> (Value) -> B?) -> [Key : B] {
var b = [Key : B]()
for (k, v) in self.mapWithKey(f) {
if let v = v {
b[k] = v
}
}
return b
}
/// MARK: Partition
/// Filters all values that do not satisfy a given predicate from the
/// receiver.
public func filter(_ pred : @escaping (Value) -> Bool) -> [Key: Value] {
return self.filterWithKey({ (_, x) -> Bool in
return pred(x)
})
}
/// Filters all keys and values that do not satisfy a given predicate from
/// the receiver.
public func filterWithKey(_ pred : (Key) -> (Value) -> Bool) -> [Key: Value] {
var d = [Key: Value]()
self.forEach {
let (k, v) = $0
if pred(k)(v) {
d[k] = v
}
}
return d
}
/// Filters all keys and values that do not satisfy a given predicate from
/// the receiver.
public func filterWithKey(_ pred : @escaping (Key, Value) -> Bool) -> [Key: Value] {
return self.filterWithKey(curry(pred))
}
/// Partitions the receiver into a Dictionary of values that passed the
/// given predicate and a Dictionary of values that failed the given
/// predicate.
public func partition(_ pred : @escaping (Value) -> Bool) -> (passed : [Key: Value], failed : [Key: Value]) {
return self.partitionWithKey({ (_, x) -> Bool in
return pred(x)
})
}
/// Partitions the receiver into a Dictionary of values that passed the
/// given predicate and a Dictionary of values that failed the given
/// predicate.
public func partitionWithKey(_ pred : (Key) -> (Value) -> Bool) -> (passed : [Key: Value], failed : [Key: Value]) {
var pass = [Key: Value]()
var fail = [Key: Value]()
self.forEach {
let (k, v) = $0
if pred(k)(v) {
pass[k] = v
} else {
fail[k] = v
}
}
return (pass, fail)
}
/// Partitions the receiver into a Dictionary of values that passed the
/// given predicate and a Dictionary of values that failed the given
/// predicate.
public func partitionWithKey(_ pred : @escaping (Key, Value) -> Bool) -> (passed : [Key: Value], failed : [Key: Value]) {
return self.partitionWithKey(curry(pred))
}
}
|
apache-2.0
|
960b82ef2e8ed9b72c94a833091ef821
| 33.336842 | 166 | 0.643164 | 3.291625 | false | false | false | false |
WirecardMobileServices/SuprAcceptSDK-iOS
|
eClear/eClear/ReceiptVC.swift
|
1
|
3022
|
//
// ReceiptVC.swift
// eClear
//
// Created by Danko, Radoslav on 16/12/2017.
// Copyright © 2017 Wirecard. All rights reserved.
//
import UIKit
import WebKit
@objc class ReceiptVC: UIViewController {
var sale:WDAcceptSaleResponse? = nil
let app:AppDelegate = UIApplication.shared.delegate as! AppDelegate
@IBOutlet weak var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(false, animated: true)
self.generateReceipt()
}
func generateReceipt(){
guard sale != nil else {
self.navigationController?.popViewController(animated: true)
app.showError("Receipt", text: "No Sale to generate the receipt from.")
return
}
if let sale = sale {
sale.receipt(true, showReturns: true, format: AcceptPrintFormat.HTML, dpi: AcceptPrintDpi.default, language:(UIApplication.shared.delegate as? AppDelegate)?.language ?? "en", completion: { ( receipts:[Any]?, error:Error?) in
if error != nil{
self.navigationController?.popViewController(animated: true)
self.app.showError("Receipt", text: error?.localizedDescription)
return
}
if let receipts = receipts {
let arrReceipts:NSArray = receipts as NSArray
let html:NSString = arrReceipts.firstObject as! NSString
if html.length > 0 {
let path = Bundle.main.bundlePath
let baseUrl = NSURL.fileURL(withPath: path)
self.webView.loadHTMLString(html as String, baseURL: baseUrl)
}
else{
self.navigationController?.popViewController(animated: true)
self.app.showError("Receipt", text: "Failed to generate the HTML receipt.")
}
}
else{
self.navigationController?.popViewController(animated: true)
self.app.showError("Receipt", text: "Failed to generate the receipt.")
}
})
}
// let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
// webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
// view.addSubview(webView)
}
}
|
mit
|
d9e007936ec0b50d1c0f414bfd767da3
| 34.964286 | 236 | 0.564383 | 5.318662 | false | false | false | false |
DianQK/LearnRxSwift
|
LearnRxSwift/Rx.playground/Pages/Other.xcplaygroundpage/Contents.swift
|
1
|
13819
|
//: [上一节](@previous) - [目录](Index)
import RxSwift
/*:
## 其他操作符
这一章节我们来看一些比较实用的操作符,虽然我归在其他中,但并不代表这不重要。
*/
/*:
## 一些实用的操作符
我们经常会用到的~ 之前的各种操作其实都有用到。
*/
/*:
### `subscribe`
操作序列的发射物和通知, `subscribe` 系列也就是连接序列和观察者的操作符,顾名思义就是订阅。
这一部分理解起来很轻松,都是同样的订阅,只是 API 的花样多一些。
下面这个是:
public func subscribe(on: (event: RxSwift.Event<Self.E>) -> Void) -> Disposable
就是说我们接收到的是事件,在这里一般通过 switch case 获取对应结果。
*/
example("subscribe") {
let sequenceOfInts = PublishSubject<Int>()
_ = sequenceOfInts
.subscribe {
print($0)
}
sequenceOfInts.on(.Next(1))
sequenceOfInts.on(.Completed)
}
/*:
### `subscribeNext`
`subscribeNext` 只订阅 Next 事件。
public func subscribeNext(onNext: (Self.E) -> Void) -> Disposable
因为只有一种事件,这里的 API 传入的就是事件中包含的具体的值了。
*/
example("subscribeNext") {
let sequenceOfInts = PublishSubject<Int>()
_ = sequenceOfInts
.subscribeNext {
print($0)
}
sequenceOfInts.on(.Next(1))
sequenceOfInts.on(.Completed)
}
/*:
### `subscribeCompleted`
`subscribeCompleted` 只订阅 Completed 事件。
public func subscribeCompleted(onCompleted: () -> Void) -> Disposable
*/
example("subscribeCompleted") {
let sequenceOfInts = PublishSubject<Int>()
_ = sequenceOfInts
.subscribeCompleted {
print("It's completed")
}
sequenceOfInts.on(.Next(1))
sequenceOfInts.on(.Completed)
}
/*:
### `subscribeError`
`subscribeError` 只订阅 Error 事件。
*/
example("subscribeError") {
let sequenceOfInts = PublishSubject<Int>()
_ = sequenceOfInts
.subscribeError { error in
print(error)
}
sequenceOfInts.on(.Next(1))
sequenceOfInts.on(.Error(NSError(domain: "Examples", code: -1, userInfo: nil)))
}
/*:
由以上几种订阅操作符,我们可以用下面这种姿势处理各种事件:
*/
example("subscribe 2") {
let sequenceOfInts = PublishSubject<Int>()
let observableOfInts = sequenceOfInts.share()
_ = observableOfInts
.subscribeNext {
print($0)
}
_ = observableOfInts
.subscribeError { error in
print(error)
}
sequenceOfInts.on(.Next(1))
sequenceOfInts.on(.Error(NSError(domain: "Examples", code: -1, userInfo: nil)))
}
/*:
当然啦,还有一个 `subscribe` 供我们使用:
public func subscribe(onNext onNext: (Self.E -> Void)? = default, onError: (ErrorType -> Void)? = default, onCompleted: (() -> Void)? = default, onDisposed: (() -> Void)? = default) -> Disposable
> 注:
你可能会看到还有一个 `subscribe` :
public func subscribeOn(scheduler: ImmediateSchedulerType) -> RxSwift.Observable<Self.E>
从返回的是一个序列可以看出这个并非是订阅操作,这是一个关于线程的故事,我们放到下一章讲解。
*/
/*:
### `doOn`
注册一个动作作为原始序列生命周期事件的占位符。
好吧,理解起来还是很迷茫的,可以参考下图:

对比其他操作符,底下的部分应该是一个序列,这里并不是。你可以把 `doOn` 理解成在任意的地方插入一个“插队订阅者”,这个“插队订阅者”不会对序列的变换造成任何影响。 `doOn` 和 `subscribe` 有很多类似的 API 。
*/
example("doOn") {
let sequenceOfInts = PublishSubject<Int>()
_ = sequenceOfInts
.doOn {
print("Intercepted event \($0)")
}
.subscribe {
print($0)
}
sequenceOfInts.on(.Next(1))
sequenceOfInts.on(.Completed)
}
/*:
## 条件和布尔操作
*/
/*:
### `takeUntil`
当另一个序列开始发射值时,忽略原序列发射的值。

*/
example("takeUntil") {
let originalSequence = PublishSubject<Int>()
let whenThisSendsNextWorldStops = PublishSubject<Int>()
_ = originalSequence
.takeUntil(whenThisSendsNextWorldStops)
.subscribe {
print($0)
}
originalSequence.on(.Next(1))
originalSequence.on(.Next(2))
originalSequence.on(.Next(3))
whenThisSendsNextWorldStops.on(.Next(1))
originalSequence.on(.Next(4))
}
/*:
不难理解,在 `whenThisSendsNextWorldStops` 发射 1 时,观察者不在关心 `originalSequence` 了。
*/
/*:
### `takeWhile`
根据一个状态判断是否继续向下发射值。这其实类似于 `filter` 。需要注意的就是 `filter` 和 `takeWhile` 什么时候更能清晰表达你的意思,就用哪个。

*/
example("takeWhile") {
let sequence = PublishSubject<Int>()
_ = sequence
.takeWhile { $0 < 4 }
.subscribe {
print($0)
}
sequence.on(.Next(1))
sequence.on(.Next(2))
sequence.on(.Next(3))
sequence.on(.Next(4))
sequence.on(.Next(5))
}
/*:
### `amb`

`amb` 用来处理发射序列的操作,不同的是, `amb` 选择先发射值的序列,自此以后都只关注这个先发射序列,抛弃其他所有序列。
有两种使用版本供选择。
*/
example("amb 1") {
let intSequence1 = PublishSubject<Int>()
let intSequence2 = PublishSubject<Int>()
let intSequence3 = PublishSubject<Int>()
let _ = [intSequence1, intSequence2, intSequence3].amb()
.subscribe {
print($0)
}
intSequence2.onNext(10) // intSequence2 最先发射
intSequence1.onNext(1)
intSequence3.onNext(100)
intSequence1.onNext(2)
intSequence3.onNext(200)
intSequence2.onNext(20)
}
example("amb 2") {
let intSequence1 = PublishSubject<Int>()
let intSequence2 = PublishSubject<Int>()
let _ = intSequence1.amb(intSequence2).subscribe { // 只用于比较两个序列
print($0)
}
intSequence2.onNext(10) // intSequence2 最先发射
intSequence1.onNext(1)
intSequence1.onNext(2)
intSequence2.onNext(20)
}
/*:
## 计算和聚合操作
*/
/*:
### `concat`
串行的合并多个序列。你可能会想起 `switchLatest` 操作符,他们有些类似,都是将序列整理到一起。不同的就是 `concat` 不会在丢弃旧序列的任何一个值。全部按照序列发射的顺序排队发射。

*/
example("concat") {
let var1 = BehaviorSubject(value: 0)
let var2 = BehaviorSubject(value: 200)
// var3 is like an Observable<Observable<Int>>
let var3 = BehaviorSubject(value: var1)
let d = var3
.concat()
.subscribe {
print($0)
}
var1.on(.Next(1))
var1.on(.Next(2))
var1.on(.Next(3))
var1.on(.Next(4))
var3.on(.Next(var2))
var2.on(.Next(201))
var1.on(.Next(5))
var1.on(.Next(6))
var1.on(.Next(7))
var1.on(.Completed)
var2.on(.Next(202))
var2.on(.Next(203))
var2.on(.Next(204))
var2.on(.Completed)
// var3.on(.Completed)
}
/*:
看到这个操作符了,说明这些操作不需要冗长的解释了。只是注意一点 `var2` 发射完毕 `var3` 并没有结束哦。
*/
/*:
### `reduce`
不多解释了,和 Swift 的 `reduce` 差不多。只是要记得它和 `scan` 一样不仅仅只是用来求和什么的。注意和 `scan` 不同 `reduce` 只发射一次,真的就和 Swift 的 `reduce` 相似。还有一个 `toArray` 的便捷操作,我想你会喜欢。

*/
example("reduce") {
_ = Observable.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
.reduce(0, accumulator: +)
.subscribe {
print($0)
}
}
/*:
## 连接操作
可连接的序列和一般的序列基本是一样的,不同的就是你可以用可连接序列调整序列发射的实际。只有当你调用 `connect` 方法时,序列才会发射。比如我们可以在所有订阅者订阅了序列后开始发射。下面的几个例子都是无限执行的,你可以自行调用每个函数感受不同的操作的结果。
*/
/*:
下面这个例子是没有进行连接操作,可以看到 5 秒之后的第二个订阅者开始订阅,于是它和第一个订阅者产生了不同步。这个时候就需要连接操作了。
*/
func sampleWithoutConnectableOperators() {
print("--- sampleWithoutConnectableOperators sample ---")
let int1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
_ = int1
.subscribe {
print("first subscription \($0)")
}
delay(5) {
_ = int1
.subscribe {
print("second subscription \($0)")
}
}
}
//sampleWithoutConnectableOperators()
/*:
### `multicast`
来看一个连接操作,这个 `multcast` 使用起来有些麻烦,不过也更强大,传入一个 Subject ,每当序列发射值时都会传个这个 Subject 。问我这有什么用,我也不清楚,不过你可以用这个做一些辅助的记录操作,至少你不应该将这个 Subject 作为主要逻辑。

*/
/*:
> 下面这个 sampleWithMulticast 请结合上面的图片理解。
*/
func sampleWithMulticast() {
print("--- sampleWithMulticast sample ---")
let subject1 = PublishSubject<Int64>()
_ = subject1
.subscribe {
print("Subject \($0)")
}
let int1 = Observable<Int64>.interval(1, scheduler: MainScheduler.instance)
.multicast(subject1)
_ = int1
.subscribe {
print("first subscription \($0)")
}
delay(2) {
int1.connect()
}
delay(4) {
_ = int1
.subscribe {
print("second subscription \($0)")
}
}
delay(6) {
_ = int1
.subscribe {
print("third subscription \($0)")
}
}
}
// sampleWithMulticast()
/*:
### `replay`
`replay` 这个操作可以让所有订阅者同一时间收到相同的值。
就相当于 `multicast` 中传入了一个 `ReplaySubject` .
publish = multicast + replay subject
> 至于其中的参数,你可以回顾一下 `ReplaySubject` 是什么,当然也有一个好玩的方法去理解他。跑一边下面的 `sampleWithReplayBuffer0` 和 `sampleWithReplayBuffer2` ,如果还不够就写一个 `sampleWithReplayBuffer4` 跑一下吧。对比一下他们的区别,记得每次只跑一个。
> `shareReplay` 就相当于将 `replay` 中的参数设置为无限大。

*/
func sampleWithReplayBuffer0() {
print("--- sampleWithReplayBuffer0 sample ---")
let int1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.replay(0)
_ = int1
.subscribe {
print("first subscription \($0)")
}
delay(2) {
int1.connect()
}
delay(4) {
_ = int1
.subscribe {
print("second subscription \($0)")
}
}
delay(6) {
_ = int1
.subscribe {
print("third subscription \($0)")
}
}
}
// sampleWithReplayBuffer0()
func sampleWithReplayBuffer2() {
print("--- sampleWithReplayBuffer2 sample ---")
let int1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.replay(2)
_ = int1
.subscribe {
print("first subscription \($0)")
}
delay(2) {
int1.connect()
}
delay(4) {
_ = int1
.subscribe {
print("second subscription \($0)")
}
}
delay(6) {
_ = int1
.subscribe {
print("third subscription \($0)")
}
}
}
// sampleWithReplayBuffer2()
/*:
### `publish`
其实这个和开始的 `sampleWithMulticast` 是一样的效果。
publish = multicast + publish subject
*/
func sampleWithPublish() {
let int1 = Observable<Int>.interval(1, scheduler: MainScheduler.instance)
.publish()
_ = int1
.subscribe {
print("first subscription \($0)")
}
delay(2) {
int1.connect()
}
delay(4) {
_ = int1
.subscribe {
print("second subscription \($0)")
}
}
delay(6) {
_ = int1
.subscribe {
print("third subscription \($0)")
}
}
}
// sampleWithPublish()
/*:
### `refCount`
这个是一个可连接序列的操作符。

它可以将一个可连接序列变成普通的序列。
*/
playgroundShouldContinueIndefinitely()
//: [目录](@Index) - [下一节 >>](@next)
|
mit
|
b86f91e8f239a8ce01418e586178d39a
| 18.446181 | 195 | 0.599411 | 3.243846 | false | false | false | false |
bhajian/raspi-remote
|
Carthage/Checkouts/ios-sdk/Source/DialogV1/Models/Node.swift
|
1
|
1586
|
/**
* Copyright IBM Corporation 2016
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
import Freddy
/** A dialog node. */
public struct Node: JSONEncodable, JSONDecodable {
/// The node's associated content.
public let content: String
/// The node's type.
public let node: String
/**
Create a `Node` with associated content and a type.
- parameter content: The node's associated content.
- parameter node: The node's type.
*/
public init(content: String, node: String) {
self.content = content
self.node = node
}
/// Used internally to initialize a `FaceTags` model from JSON.
public init(json: JSON) throws {
content = try json.string("content")
node = try json.string("node")
}
/// Used internally to initialize a `FaceTags` model from JSON.
public func toJSON() -> JSON {
var json = [String: JSON]()
json["content"] = .String(content)
json["node"] = .String(node)
return JSON.Dictionary(json)
}
}
|
mit
|
b897d10a3b86e99d6e0b21c5da8674e1
| 28.924528 | 75 | 0.656999 | 4.298103 | false | false | false | false |
AliceAponasko/LJReader
|
LJReader/Extensions/UIViewControllerExtension.swift
|
1
|
1820
|
//
// UIViewControllerExtension.swift
// LJReader
//
// Created by Alice Aponasko on 9/11/16.
// Copyright © 2016 aliceaponasko. All rights reserved.
//
import UIKit
extension UIViewController {
func emptyResultsView(title: String) -> UIView {
let emptyView = UIView(frame: CGRect(
x: 0,
y: 0,
width: view.frame.width,
height: 200))
let emptyResultsLabel = UILabel()
emptyResultsLabel.text = title
emptyResultsLabel.textAlignment = .Center
emptyResultsLabel.numberOfLines = 0
emptyView.addSubview(emptyResultsLabel)
emptyResultsLabel.translatesAutoresizingMaskIntoConstraints = false
emptyView.addConstraint(NSLayoutConstraint(
item: emptyResultsLabel,
attribute: .Top,
relatedBy: .Equal,
toItem: emptyView,
attribute: .Top,
multiplier: 1,
constant: 0))
emptyView.addConstraint(NSLayoutConstraint(
item: emptyResultsLabel,
attribute: .Height,
relatedBy: .Equal,
toItem: nil,
attribute: .NotAnAttribute,
multiplier: 1,
constant: emptyView.frame.height))
emptyView.addConstraint(NSLayoutConstraint(
item: emptyResultsLabel,
attribute: .Right,
relatedBy: .Equal,
toItem: emptyView,
attribute: .Right,
multiplier: 1,
constant: 0))
emptyView.addConstraint(NSLayoutConstraint(
item: emptyResultsLabel,
attribute: .Left,
relatedBy: .Equal,
toItem: emptyView,
attribute: .Left,
multiplier: 1,
constant: 0))
return emptyView
}
}
|
mit
|
874180f343ba4649554e90386caa3a07
| 27.873016 | 75 | 0.575591 | 5.138418 | false | false | false | false |
AFathi/NotchToolkit
|
Example/NotchToolkit-Example/NotchImageViewController.swift
|
1
|
2026
|
//
// NotchImageViewController.swift
// NotchToolkit-Example
//
// Created by Ahmed Bekhit on 11/8/17.
// Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved.
//
import UIKit
import NotchToolkit
// MARK: - Implement NotchToolkit
//Step 1. add `NotchToolbarDelegate`
//Step 2. implement delegate functions, check NotchToolkit Delegates
class NotchImageViewController: UIViewController {
//Step 3. initialize `NotchImageView`
var imageView: NotchImageView?
override func viewDidLoad() {
super.viewDidLoad()
imageView = NotchImageView(image: UIImage(named:"tst_img.JPG"))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
// MARK: - NotchToolkit Delegate Methods
extension NotchImageViewController: NotchToolbarDelegate {
func deviceDidRotate() {
//Step 5. call `autoResize` in the `deviceDidRotate` function
imageView?.autoResize()
}
// This delegate function allows you to detect which toolbar icon was selected.
func didTapToolIcon(_ tools: UICollectionView, toolIndex: IndexPath, section: Int, row: Int) {
}
}
// MARK: - ViewController Buttons IBAction
extension NotchImageViewController {
@IBAction func loadNotchImage(_ sender: UIButton) {
if !(imageView?.isVisible)! {
sender.setTitle("Delete Image Object", for: .normal)
imageView?.durationIntervals = 2.8
imageView?.printBarColor = .red
imageView?.printBarHeight = 5
imageView?.delegate = self
imageView?.prepare(in: self)
imageView?.load()
self.view.insertSubview(sender, aboveSubview: imageView!)
}else{
sender.setTitle("Load Image from Notch", for: .normal)
imageView?.remove()
imageView = NotchImageView(image: UIImage(named:"tst_img.JPG"))
}
}
@IBAction func goBack(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
|
mit
|
388faeea35bf3761932b48fca7e71d71
| 29.681818 | 98 | 0.662222 | 4.550562 | false | false | false | false |
almazrafi/Metatron
|
Tests/MetatronTests/ID3v2/ID3v2FrameSetTest.swift
|
1
|
7480
|
//
// ID3v2FrameSetTest.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import Metatron
class ID3v2FrameSetTest: XCTestCase {
// MARK: Instance Methods
func testInit() {
do {
let frameSet = ID3v2FrameSet(identifier: ID3v2FrameID.tofn)
XCTAssert(frameSet.identifier == ID3v2FrameID.tofn)
XCTAssert(frameSet.frames.count == 1)
XCTAssert(frameSet.mainFrame == frameSet.frames[0])
}
do {
let frames: [ID3v2Frame] = [ID3v2Frame(identifier: ID3v2FrameID.uslt),
ID3v2Frame(identifier: ID3v2FrameID.uslt),
ID3v2Frame(identifier: ID3v2FrameID.uslt)]
let frameSet = ID3v2FrameSet(frames: frames)
XCTAssert(frameSet.identifier == ID3v2FrameID.uslt)
XCTAssert(frameSet.frames.count == 3)
XCTAssert(frameSet.mainFrame == frames[0])
XCTAssert(frameSet.frames[0] == frames[0])
XCTAssert(frameSet.frames[1] == frames[1])
XCTAssert(frameSet.frames[2] == frames[2])
}
do {
let frames: [ID3v2Frame] = [ID3v2Frame(identifier: ID3v2FrameID.uslt),
ID3v2Frame(identifier: ID3v2FrameID.toly),
ID3v2Frame(identifier: ID3v2FrameID.uslt)]
let frameSet = ID3v2FrameSet(frames: frames)
XCTAssert(frameSet.identifier == ID3v2FrameID.uslt)
XCTAssert(frameSet.frames.count == 2)
XCTAssert(frameSet.mainFrame == frames[0])
XCTAssert(frameSet.frames[0] == frames[0])
XCTAssert(frameSet.frames[1] == frames[2])
}
}
func testRemoveFrame() {
let frames: [ID3v2Frame] = [ID3v2Frame(identifier: ID3v2FrameID.txxx),
ID3v2Frame(identifier: ID3v2FrameID.txxx),
ID3v2Frame(identifier: ID3v2FrameID.txxx)]
let frameSet = ID3v2FrameSet(frames: frames)
do {
XCTAssert(frameSet.removeFrame(frames[0]) == true)
XCTAssert(frameSet.removeFrame(frames[0]) == false)
XCTAssert(frameSet.identifier == ID3v2FrameID.txxx)
XCTAssert(frameSet.frames.count == 2)
XCTAssert(frameSet.mainFrame == frames[1])
}
do {
frameSet.removeFrame(at: 0)
XCTAssert(frameSet.removeFrame(frames[1]) == false)
XCTAssert(frameSet.identifier == ID3v2FrameID.txxx)
XCTAssert(frameSet.frames.count == 1)
XCTAssert(frameSet.mainFrame == frames[2])
}
do {
XCTAssert(frameSet.removeFrame(frames[2]) == true)
XCTAssert(frameSet.removeFrame(frames[2]) == false)
XCTAssert(frameSet.identifier == ID3v2FrameID.txxx)
XCTAssert(frameSet.frames.count == 1)
XCTAssert(frameSet.mainFrame != frames[2])
}
}
func testAppendFrame() {
let frameSet = ID3v2FrameSet(identifier: ID3v2FrameID.wxxx)
do {
let frame = frameSet.appendFrame()
XCTAssert(frameSet.identifier == ID3v2FrameID.wxxx)
XCTAssert(frameSet.frames.count == 2)
XCTAssert(frameSet.mainFrame != frame)
XCTAssert(frameSet.frames[1] == frame)
}
do {
let frame = frameSet.appendFrame()
XCTAssert(frameSet.identifier == ID3v2FrameID.wxxx)
XCTAssert(frameSet.frames.count == 3)
XCTAssert(frameSet.mainFrame != frame)
XCTAssert(frameSet.frames[2] == frame)
}
}
func testReset() {
let frames: [ID3v2Frame] = [ID3v2Frame(identifier: ID3v2FrameID.txxx),
ID3v2Frame(identifier: ID3v2FrameID.txxx),
ID3v2Frame(identifier: ID3v2FrameID.txxx)]
do {
frames[0].tagAlterPreservation = true
frames[0].fileAlterPreservation = true
frames[0].readOnly = true
frames[0].unsynchronisation = true
frames[0].dataLengthIndicator = true
frames[0].compression = 6
frames[0].group = 128
let stuff = frames[0].imposeStuff(format: ID3v2UnknownValueFormat.regular)
for _ in 0..<123 {
stuff.content.append(UInt8(arc4random_uniform(256)))
}
}
do {
frames[1].tagAlterPreservation = true
frames[1].fileAlterPreservation = true
frames[1].readOnly = true
frames[1].unsynchronisation = true
frames[1].dataLengthIndicator = true
frames[1].compression = 6
frames[1].group = nil
let stuff = frames[1].imposeStuff(format: ID3v2UnknownValueFormat.regular)
for _ in 0..<123 {
stuff.content.append(UInt8(arc4random_uniform(256)))
}
}
do {
frames[2].tagAlterPreservation = true
frames[2].fileAlterPreservation = true
frames[2].readOnly = true
frames[2].unsynchronisation = true
frames[2].dataLengthIndicator = true
frames[2].compression = 0
frames[2].group = 128
let stuff = frames[2].imposeStuff(format: ID3v2UnknownValueFormat.regular)
for _ in 0..<123 {
stuff.content.append(UInt8(arc4random_uniform(256)))
}
}
let frameSet = ID3v2FrameSet(frames: frames)
frameSet.reset()
XCTAssert(frameSet.identifier == ID3v2FrameID.txxx)
XCTAssert(frameSet.mainFrame == frames[0])
XCTAssert(frameSet.frames.count == 1)
XCTAssert(frameSet.mainFrame.isEmpty)
XCTAssert(frameSet.mainFrame.stuff == nil)
XCTAssert(frameSet.mainFrame.tagAlterPreservation == false)
XCTAssert(frameSet.mainFrame.fileAlterPreservation == false)
XCTAssert(frameSet.mainFrame.readOnly == false)
XCTAssert(frameSet.mainFrame.unsynchronisation == false)
XCTAssert(frameSet.mainFrame.dataLengthIndicator == false)
XCTAssert(frameSet.mainFrame.compression == 0)
XCTAssert(frameSet.mainFrame.group == nil)
}
}
|
mit
|
23e22913d6bd9d3d68edc08017e7ff8e
| 32.244444 | 86 | 0.601337 | 4.130315 | false | false | false | false |
jeffreybergier/WaterMe2
|
WaterMe/Frameworks/Datum/Datum/Wrapper/ReminderVessel/ReminderVesselWrapper.swift
|
1
|
1819
|
//
// ReminderVesselWrapper.swift
// Datum
//
// Created by Jeffrey Bergier on 2020/05/15.
// Copyright © 2020 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
public protocol ReminderVessel: ModelCompleteCheckable {
var uuid: String { get }
var displayName: String? { get }
var icon: ReminderVesselIcon? { get }
var kind: ReminderVesselKind { get }
var isModelComplete: ModelCompleteError? { get }
var shortLabelSafeDisplayName: String? { get }
func observe(_ block: @escaping (ReminderVesselChange) -> Void) -> ObservationToken
func observeReminders(_ block: @escaping (ReminderCollectionChange) -> Void) -> ObservationToken
}
public struct ReminderVesselChanges {
public var changedDisplayName = false
public var changedIconEmoji = false
public var changedReminders = false
public var changedPointlessBloop = false
}
public typealias ReminderVesselChange = ItemChange<ReminderVesselChanges>
public typealias ReminderVesselCollection = AnyCollection<ReminderVessel, Int>
public typealias ReminderVesselCollectionChange = CollectionChange<ReminderVesselCollection, Int>
|
gpl-3.0
|
2d3c941d461232ee5bbf6061e828c7e9
| 40.318182 | 100 | 0.750825 | 4.5 | false | false | false | false |
LesCoureurs/Courir
|
Courir/Courir/ObstacleGenerator.swift
|
1
|
1070
|
//
// ObstacleGenerator.swift
// Courir
//
// Created by Sebastian Quek on 19/3/16.
// Copyright © 2016 NUS CS3217. All rights reserved.
//
import GameplayKit
class ObstacleGenerator {
private let source: GKARC4RandomSource
var seed: NSData {
return source.seed
}
init(seed: NSData? = nil) {
if seed != nil && seed?.length != 0 {
source = GKARC4RandomSource(seed: seed!)
} else {
source = GKARC4RandomSource()
}
}
func getNextObstacle(type: ObstacleType? = nil) -> Obstacle? {
if let type = type {
return Obstacle(type: type)
}
let nextRandFloat = source.nextUniform()
switch nextRandFloat {
case 0..<floatingProbability:
return Obstacle(type: ObstacleType.Floating)
case floatingProbability..<floatingProbability + nonfloatingProbability:
return Obstacle(type: ObstacleType.NonFloating)
default:
return nil
}
}
}
|
mit
|
d6a428cff5541668d9e1444a997b4898
| 24.452381 | 84 | 0.571562 | 4.472803 | false | false | false | false |
HeartOfCarefreeHeavens/TestKitchen_pww
|
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRedPacketCell.swift
|
1
|
7239
|
//
// CBRedPacketCell.swift
// TestKitchen
//
// Created by qianfeng on 16/8/18.
// Copyright © 2016年 qianfeng. All rights reserved.
//
import UIKit
class CBRedPacketCell: UITableViewCell {
@IBOutlet weak var scrollView: UIScrollView!
//显示数据
var model:CBRecommendWidgetListModel?{
didSet{
showData()
}
}
//显示文字图片
func showData(){
for sub in scrollView.subviews {
sub.removeFromSuperview()
}
//1.容器视图
let containerView = UIView.createView()
scrollView.addSubview(containerView)
containerView.snp_makeConstraints {
[weak self]
(make) in
make.edges.equalTo(self!.scrollView)
make.height.equalTo(self!.scrollView.snp_height)
}
var lastView:UIView? = nil
let cnt = model?.widget_data?.count
if cnt > 0 {
for i in 0..<cnt!{
let imageModel = model?.widget_data![i]
//显示在线图片
if imageModel?.type == "image" {
let imageView = UIImageView.createImageView(nil)
let url = NSURL(string: (imageModel?.content)!)
imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named:"sdefaultImage" ), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
containerView.addSubview(imageView)
//约束
imageView.snp_makeConstraints(closure: { (make) in
make.top.bottom.equalTo(containerView)
make.width.equalTo(180)
if i == 0{
make.left.equalTo(0)
}else{
make.left.equalTo(lastView!.snp_right)
}
})
//添加点击事件
imageView.userInteractionEnabled = true
imageView.tag = 400 + i
let g = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
imageView.addGestureRecognizer(g)
lastView = imageView
}
}
containerView.snp_makeConstraints(closure: { (make) in
make.right.equalTo((lastView?.snp_right)!)
})
}
}
func tapAction(g:UIGestureRecognizer){
let index = (g.view?.tag)! - 400
print(index)
}
class func createRedPackageCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withListModel listModel:CBRecommendWidgetListModel)->CBRedPacketCell{
let cellId = "redPacketCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBRedPacketCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CBRedPacketCell", owner: nil, options: nil).last as? CBRedPacketCell
}
cell?.model = listModel
return cell!
}
// //显示数据
// var model: CBRecommendWidgetListModel? {
// didSet {
// showData()
// }
// }
//
// //显示图片和文字
// func showData(){
//
//
// self.scrollView.showsHorizontalScrollIndicator = false
// //1.容器视图
// let container = UIView.createView()
// scrollView.addSubview(container)
//
// //约束
// container.snp_makeConstraints {
// [weak self]
// (make) in
// make.edges.equalTo(self!.scrollView)
// make.height.equalTo(self!.scrollView.snp_height)
// }
//
// //2.循环添加图片
// var lastView: UIView? = nil
// let cnt = model?.widget_data?.count
// if cnt > 0 {
// for i in 0..<cnt! {
//
// let imageModel = model?.widget_data![i]
//
// if imageModel?.type == "image" {
//
// //显示在线图片
// let imageView = UIImageView.createImageView(nil)
// let url = NSURL(string: (imageModel?.content)!)
// imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sdefaultImage"), optionsInfo: nil, progressBlock: nil, completionHandler: nil)
// container.addSubview(imageView)
//
// //约束
// imageView.snp_makeConstraints(closure: { (make) in
// make.top.bottom.equalTo(container)
// make.width.equalTo(180)
// if i == 0 {
// make.left.equalTo(0)
// }else{
// make.left.equalTo((lastView?.snp_right)!)
// }
// })
//
// //添加点击事件
// imageView.userInteractionEnabled = true
// imageView.tag = 400+i
// //手势
// let g = UITapGestureRecognizer(target: self, action: #selector(tapAction(_:)))
// imageView.addGestureRecognizer(g)
//
//
// lastView = imageView
// }
//
//
//
//
// }
//
// //修改容器的大小
// container.snp_makeConstraints(closure: { (make) in
// make.right.equalTo((lastView?.snp_right)!)
// })
//
//
// }
//
//
// }
//
//
// func tapAction(g: UIGestureRecognizer) {
//
// let index = (g.view?.tag)!-400
// print(index)
// }
//
//
// //创建cell的方法
// class func createRedPackageCellFor(tableView: UITableView,atIndexPath indexPath: NSIndexPath,withListModel listModel: CBRecommendWidgetListModel) -> CBRedPacketCell{
//
// let cellId = "redPacketCellId"
//
// var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBRedPacketCell
// if nil == cell {
// cell = NSBundle.mainBundle().loadNibNamed("CBRedPacketCell", owner: nil, options: nil).last as? CBRedPacketCell
// }
//
// cell?.model = listModel
//
// return cell!
// }
//
//
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
|
mit
|
c089673de256213c75a18c953e0e5a0a
| 28.864979 | 171 | 0.465244 | 5.044904 | false | false | false | false |
sharath-cliqz/browser-ios
|
Client/Application/AppDelegate.swift
|
2
|
33574
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Shared
import Storage
import AVFoundation
import XCGLogger
import MessageUI
import WebImage
import SwiftKeychainWrapper
import LocalAuthentication
private let log = Logger.browserLogger
let LatestAppVersionProfileKey = "latestAppVersion"
let AllowThirdPartyKeyboardsKey = "settings.allowThirdPartyKeyboards"
private let InitialPingSentKey = "initialPingSent"
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var normalModeBgImage: UIImageView?
var forgetModeBgImage: UIImageView?
var browserViewController: BrowserViewController!
var rootViewController: UIViewController!
weak var profile: BrowserProfile?
var tabManager: TabManager!
var adjustIntegration: AdjustIntegration?
var foregroundStartTime = 0
weak var application: UIApplication?
var launchOptions: [AnyHashable: Any]?
let appVersion = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
var openInFirefoxParams: LaunchParams? = nil
var appStateStore: AppStateStore!
var systemBrightness: CGFloat = UIScreen.main.brightness
//Cliqz: capacity limits for URLCache
let CacheMemoryCapacity = 8 * 1024 * 1024
let CacheDiskCapacity = 50 * 1024 * 1024
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
AppStatus.sharedInstance.appWillFinishLaunching()
//Cliqz: Configure URL Cache; set memoryCapacity to 8MB, and diskCapacity to 50MB
let urlCache = URLCache(memoryCapacity: CacheMemoryCapacity, diskCapacity: CacheDiskCapacity, diskPath: nil)
URLCache.shared = urlCache
// Hold references to willFinishLaunching parameters for delayed app launch
self.application = application
self.launchOptions = launchOptions
log.debug("Configuring window…")
self.window = CliqzMainWindow(frame: UIScreen.main.bounds)
self.window!.backgroundColor = UIConstants.AppBackgroundColor
SubscriptionsHandler.sharedInstance.configureRemoteNotifications()
// Short c ircuit the app if we want to email logs from the debug menu
if DebugSettingsBundleOptions.launchIntoEmailComposer {
self.window?.rootViewController = UIViewController()
presentEmailComposerWithLogs()
return true
} else {
return startApplication(application, withLaunchOptions: launchOptions)
}
}
fileprivate func startApplication(_ application: UIApplication, withLaunchOptions launchOptions: [AnyHashable: Any]?) -> Bool {
// Cliqz: Starting Sentry for crash reporting
let sendCrashReports = SettingsPrefs.shared.getSendCrashReportsPref()
Sentry.shared.setup(sendCrashReports: sendCrashReports)
log.debug("Setting UA…")
// Set the Firefox UA for browsing.
setUserAgent()
log.debug("Starting keyboard helper…")
// Start the keyboard helper to monitor and cache keyboard state.
KeyboardHelper.defaultHelper.startObserving()
log.debug("Starting dynamic font helper…")
DynamicFontHelper.defaultHelper.startObserving()
log.debug("Setting custom menu items…")
MenuHelper.defaultHelper.setItems()
// Cliqz: Removed logger inisialization because of performance considerations and also we don't need FF logger.
// log.debug("Creating Sync log file…")
// let logDate = Date()
// // Create a new sync log file on cold app launch. Note that this doesn't roll old logs.
// Logger.syncLogger.newLogWithDate(logDate)
//
// log.debug("Creating corrupt DB logger…")
// Logger.corruptLogger.newLogWithDate(logDate)
//
// log.debug("Creating Browser log file…")
// Logger.browserLogger.newLogWithDate(logDate)
log.debug("Getting profile…")
let profile = getProfile(application)
appStateStore = AppStateStore(prefs: profile.prefs)
SettingsPrefs.shared.profile = profile
log.debug("Initializing telemetry…")
Telemetry.initWithPrefs(profile.prefs)
if !DebugSettingsBundleOptions.disableLocalWebServer {
log.debug("Starting web server…")
// Set up a web server that serves us static content. Do this early so that it is ready when the UI is presented.
setUpWebServer(profile)
}
log.debug("Setting AVAudioSession category…")
do {
// for aural progress bar: play even with silent switch on, and do not stop audio from other apps (like music)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
} catch _ {
log.error("Failed to assign AVAudioSession category to allow playing with silent switch on for aural progress bar")
}
let imageStore = DiskImageStore(files: profile.files, namespace: "TabManagerScreenshots", quality: UIConstants.ScreenshotQuality)
log.debug("Configuring tabManager…")
self.tabManager = TabManager(prefs: profile.prefs, imageStore: imageStore)
self.tabManager.stateDelegate = self
// Add restoration class, the factory that will return the ViewController we
// will restore with.
log.debug("Initing BVC…")
browserViewController = BrowserViewController(profile: self.profile!, tabManager: self.tabManager)
browserViewController.restorationIdentifier = NSStringFromClass(BrowserViewController.self)
browserViewController.restorationClass = AppDelegate.self as? UIViewControllerRestoration.Type
SubscriptionsHandler.sharedInstance.delegate = browserViewController
let navigationController = UINavigationController(rootViewController: browserViewController)
navigationController.delegate = self
navigationController.isNavigationBarHidden = true
if AppConstants.MOZ_STATUS_BAR_NOTIFICATION {
rootViewController = NotificationRootViewController(rootViewController: navigationController)
} else {
rootViewController = navigationController
}
self.window!.rootViewController = rootViewController
self.normalModeBgImage = UIImageView(image: UIImage.fullBackgroundImage())
self.forgetModeBgImage = UIImageView(image: UIImage(named: "forgetModeBgImage"))
// Cliqz: disable crash reporting
// do {
// log.debug("Configuring Crash Reporting...")
// try PLCrashReporter.sharedReporter().enableCrashReporterAndReturnError()
// } catch let error as NSError {
// log.error("Failed to enable PLCrashReporter - \(error.description)")
// }
log.debug("Adding observers…")
NotificationCenter.default.addObserver(forName: NSNotification.Name.FSReadingListAddReadingListItem, object: nil, queue: nil) { (notification) -> Void in
if let userInfo = notification.userInfo, let url = userInfo["URL"] as? URL {
let title = (userInfo["Title"] as? String) ?? ""
profile.readingList?.createRecordWithURL(url.absoluteString, title: title, addedBy: UIDevice.current.name)
}
}
// check to see if we started 'cos someone tapped on a notification.
if let localNotification = launchOptions?[UIApplicationLaunchOptionsKey.localNotification] as? UILocalNotification {
viewURLInNewTab(localNotification)
}
adjustIntegration = AdjustIntegration(profile: profile)
// We need to check if the app is a clean install to use for
// preventing the What's New URL from appearing.
if getProfile(application).prefs.intForKey(IntroViewControllerSeenProfileKey) == nil {
getProfile(application).prefs.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey)
}
log.debug("Updating authentication keychain state to reflect system state")
self.updateAuthenticationInfo()
SystemUtils.onFirstRun()
resetForegroundStartTime()
if !(profile.prefs.boolForKey(InitialPingSentKey) ?? false) {
// Try to send an initial core ping when the user first opens the app so that they're
// "on the map". This lets us know they exist if they try the app once, crash, then uninstall.
// sendCorePing() only sends the ping if the user is offline, so if the first ping doesn't
// go through *and* the user crashes then uninstalls on the first run, then we're outta luck.
profile.prefs.setBool(true, forKey: InitialPingSentKey)
sendCorePing()
}
sendCorePing()
//Turn on the bloomFilter
BloomFilterManager.sharedInstance.turnOn()
log.debug("Done with setting up the application.")
return true
}
func applicationWillTerminate(_ application: UIApplication) {
log.debug("Application will terminate.")
// We have only five seconds here, so let's hope this doesn't take too long.
self.profile?.shutdown()
// Allow deinitializers to close our database connections.
self.profile = nil
self.tabManager = nil
self.browserViewController = nil
self.rootViewController = nil
AppStatus.sharedInstance.appWillTerminate()
}
/**
* We maintain a weak reference to the profile so that we can pause timed
* syncs when we're backgrounded.
*
* The long-lasting ref to the profile lives in BrowserViewController,
* which we set in application:willFinishLaunchingWithOptions:.
*
* If that ever disappears, we won't be able to grab the profile to stop
* syncing... but in that case the profile's deinit will take care of things.
*/
func getProfile(_ application: UIApplication) -> Profile {
if let profile = self.profile {
return profile
}
let p = BrowserProfile(localName: "profile", app: application)
self.profile = p
p.offrzDataSource = OffrzDataSource()
return p
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
AppStatus.sharedInstance.appDidFinishLaunching()
// Override point for customization after application launch.
let shouldPerformAdditionalDelegateHandling = true
log.debug("Did finish launching.")
log.debug("Setting up Adjust")
self.adjustIntegration?.triggerApplicationDidFinishLaunchingWithOptions(launchOptions)
log.debug("Making window key and visible…")
self.window!.makeKeyAndVisible()
// Cliqz: changed the tint color of window (ActionSheets, AlertViews, NavigationBar)
self.window!.tintColor = UIConstants.CliqzThemeColor
// Now roll logs.
log.debug("Triggering log roll.")
// Cliqz: disabled calling to syncLogger
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
// Logger.syncLogger.deleteOldLogsDownToSizeLimit()
// Logger.browserLogger.deleteOldLogsDownToSizeLimit()
// }
// Cliqz: comented Firefox 3D Touch code
// if #available(iOS 9, *) {
// // If a shortcut was launched, display its information and take the appropriate action
// if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
//
// QuickActions.sharedInstance.launchedShortcutItem = shortcutItem
// // This will block "performActionForShortcutItem:completionHandler" from being called.
// shouldPerformAdditionalDelegateHandling = false
// }
// }
// Cliqz: Added Lookback integration
#if BETA
// Lookback.setupWithAppToken("HWiD4ErSbeNy9JcRg")
// Lookback.sharedLookback().shakeToRecord = true
// Lookback.sharedLookback() = false
#endif
// Configure AntiTracking/AdBlocking Module
AntiTrackingModule.sharedInstance.initModule()
AdblockingModule.sharedInstance.initModule()
log.debug("Done with applicationDidFinishLaunching.")
return shouldPerformAdditionalDelegateHandling
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false) else {
return false
}
guard let urlTypes = Bundle.main.object(forInfoDictionaryKey: "CFBundleURLTypes") as? [AnyObject],
let urlSchemes = urlTypes.first?["CFBundleURLSchemes"] as? [String] else {
// Something very strange has happened; org.mozilla.Client should be the zeroeth URL type.
log.error("Custom URL schemes not available for validating")
return false
}
guard let scheme = components.scheme, urlSchemes.contains(scheme) else {
log.warning("Cannot handle \(components.scheme) URL scheme")
return false
}
var url: String?
var isPrivate: Bool = false
for item in (components.queryItems ?? []) as [URLQueryItem] {
switch item.name {
case "url":
url = item.value
case "private":
isPrivate = NSString(string: item.value ?? "false").boolValue
default: ()
}
}
let params: LaunchParams
if let url = url, let newURL = URL(string: url) {
params = LaunchParams(url: newURL, isPrivate: isPrivate)
} else {
params = LaunchParams(url: nil, isPrivate: isPrivate)
}
if application.applicationState == .active {
// If we are active then we can ask the BVC to open the new tab right away.
// Otherwise, we remember the URL and we open it in applicationDidBecomeActive.
launchFromURL(params)
} else {
openInFirefoxParams = params
}
return true
}
func launchFromURL(_ params: LaunchParams) {
let isPrivate = params.isPrivate ?? false
if let newURL = params.url {
self.browserViewController.openURLInNewTab(newURL, isPrivate: isPrivate)
} else {
self.browserViewController.openBlankNewTabAndFocus(isPrivate: isPrivate)
}
}
func application(_ application: UIApplication, shouldAllowExtensionPointIdentifier extensionPointIdentifier: UIApplicationExtensionPointIdentifier) -> Bool {
// Cliqz: Commented third party keyboard handler. We shouldn't allow any third party keyboard.
/*
if let thirdPartyKeyboardSettingBool = getProfile(application).prefs.boolForKey(AllowThirdPartyKeyboardsKey) where extensionPointIdentifier == UIApplicationKeyboardExtensionPointIdentifier {
return thirdPartyKeyboardSettingBool
}
return true
*/
return false
}
// We sync in the foreground only, to avoid the possibility of runaway resource usage.
// Eventually we'll sync in response to notifications.
func applicationDidBecomeActive(_ application: UIApplication) {
AppStatus.sharedInstance.appDidBecomeActive(self.profile!)
guard !DebugSettingsBundleOptions.launchIntoEmailComposer else {
return
}
NightModeHelper.restoreNightModeBrightness((self.profile?.prefs)!, toForeground: true)
self.profile?.syncManager.applicationDidBecomeActive()
//Cliqz: disable loading queued tables
// We could load these here, but then we have to futz with the tab counter
// and making NSURLRequests.
// self.browserViewController.loadQueuedTabs()
// handle quick actions is available
if #available(iOS 9, *) {
let quickActions = QuickActions.sharedInstance
if let shortcut = quickActions.launchedShortcutItem {
// dispatch asynchronously so that BVC is all set up for handling new tabs
// when we try and open them
quickActions.handleShortCutItem(shortcut, withBrowserViewController: browserViewController)
quickActions.launchedShortcutItem = nil
}
// we've removed the Last Tab option, so we should remove any quick actions that we already have that are last tabs
// we do this after we've handled any quick actions that have been used to open the app so that we don't b0rk if
// the user has opened the app for the first time after upgrade with a Last Tab quick action
QuickActions.sharedInstance.removeDynamicApplicationShortcutItemOfType(ShortcutType.OpenLastTab, fromApplication: application)
}
// Check if we have a URL from an external app or extension waiting to launch,
// then launch it on the main thread.
if let params = openInFirefoxParams {
openInFirefoxParams = nil
DispatchQueue.main.async {
self.launchFromURL(params)
}
}
// Cliqz: Added to confire home shortcuts
if #available(iOS 9.0, *) {
self.configureHomeShortCuts()
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Cliq: notify the AppStatus that the app entered background
AppStatus.sharedInstance.appDidEnterBackground()
// Workaround for crashing in the background when <select> popovers are visible (rdar://24571325).
let jsBlurSelect = "if (document.activeElement && document.activeElement.tagName === 'SELECT') { document.activeElement.blur(); }"
tabManager.selectedTab?.webView?.evaluateJavaScript(jsBlurSelect, completionHandler: nil)
syncOnDidEnterBackground(application: application)
let elapsed = Int(Date().timeIntervalSince1970) - foregroundStartTime
Telemetry.recordEvent(UsageTelemetry.makeEvent(elapsed))
sendCorePing()
// Cliqz: Clear cache whenever the app goes to background
var taskId: UIBackgroundTaskIdentifier = UIBackgroundTaskInvalid
taskId = application.beginBackgroundTask { _ in
application.endBackgroundTask(taskId)
}
self.clearCache()
application.endBackgroundTask(taskId)
}
// Cliqz: clear cache if the cache size exceed predified limits
private func clearCache() {
let currentMemoryUsage = URLCache.shared.currentMemoryUsage
let currentDiskUsage = URLCache.shared.currentDiskUsage
if currentMemoryUsage > CacheMemoryCapacity || currentDiskUsage > CacheDiskCapacity {
let cacheClearable = CacheClearable(tabManager: self.tabManager)
cacheClearable.clear()
}
}
fileprivate func syncOnDidEnterBackground(application: UIApplication) {
// Short circuit and don't sync if we don't have a syncable account.
guard self.profile?.hasSyncableAccount() ?? false else {
return
}
self.profile?.syncManager.applicationDidEnterBackground()
var taskId: UIBackgroundTaskIdentifier = 0
taskId = application.beginBackgroundTask (expirationHandler: { _ in
log.warning("Running out of background time, but we have a profile shutdown pending.")
self.profile?.shutdown()
application.endBackgroundTask(taskId)
})
let backgroundQueue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background)
self.profile?.syncManager.syncEverything().uponQueue(backgroundQueue) { _ in
self.profile?.shutdown()
application.endBackgroundTask(taskId)
}
}
func applicationWillResignActive(_ application: UIApplication) {
NightModeHelper.restoreNightModeBrightness((self.profile?.prefs)!, toForeground: false)
// Cliqz: notify AppStatus that the app will resign active
AppStatus.sharedInstance.appWillResignActive()
}
func applicationWillEnterForeground(_ application: UIApplication) {
// The reason we need to call this method here instead of `applicationDidBecomeActive`
// is that this method is only invoked whenever the application is entering the foreground where as
// `applicationDidBecomeActive` will get called whenever the Touch ID authentication overlay disappears.
self.updateAuthenticationInfo()
// Cliqz: call AppStatus
AppStatus.sharedInstance.appWillEnterForeground()
resetForegroundStartTime()
profile?.reopen()
}
fileprivate func resetForegroundStartTime() {
foregroundStartTime = Int(Date().timeIntervalSince1970)
}
/// Send a telemetry ping if the user hasn't disabled reporting.
/// We still create and log the ping for non-release channels, but we don't submit it.
fileprivate func sendCorePing() {
guard let profile = profile, (profile.prefs.boolForKey("settings.sendUsageData") ?? true) else {
log.debug("Usage sending is disabled. Not creating core telemetry ping.")
return
}
DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background).async {
// The core ping resets data counts when the ping is built, meaning we'll lose
// the data if the ping doesn't go through. To minimize loss, we only send the
// core ping if we have an active connection. Until we implement a fault-handling
// telemetry layer that can resend pings, this is the best we can do.
guard DeviceInfo.hasConnectivity() else {
log.debug("No connectivity. Not creating core telemetry ping.")
return
}
let ping = CorePing(profile: profile)
Telemetry.sendPing(ping)
}
}
fileprivate func updateAuthenticationInfo() {
if let authInfo = KeychainWrapper.sharedAppContainerKeychain.authenticationInfo() {
if !LAContext().canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) {
authInfo.useTouchID = false
KeychainWrapper.sharedAppContainerKeychain.setAuthenticationInfo(authInfo)
}
}
}
fileprivate func setUpWebServer(_ profile: Profile) {
let server = WebServer.sharedInstance
ReaderModeHandlers.register(server, profile: profile)
ErrorPageHelper.register(server, certStore: profile.certStore)
AboutHomeHandler.register(server)
AboutLicenseHandler.register(server)
AboutEulaHandler.register(server)
SessionRestoreHandler.register(server)
ShareCardHelper.register(server)
// Cliqz: Registered trampolineForward to be able to load it via URLRequest
server.registerMainBundleResource("trampolineForward.html", module: "cliqz")
// Cliqz: starting the navigation extension
NavigationExtension.start()
// Bug 1223009 was an issue whereby CGDWebserver crashed when moving to a background task
// catching and handling the error seemed to fix things, but we're not sure why.
// Either way, not implicitly unwrapping a try is not a great way of doing things
// so this is better anyway.
do {
try server.start()
} catch let err as NSError {
log.error("Unable to start WebServer \(err)")
}
}
fileprivate func setUserAgent() {
let firefoxUA = UserAgent.defaultUserAgent()
// Set the UA for WKWebView (via defaults), the favicon fetcher, and the image loader.
// This only needs to be done once per runtime. Note that we use defaults here that are
// readable from extensions, so they can just use the cached identifier.
let defaults = UserDefaults(suiteName: AppInfo.sharedContainerIdentifier())!
defaults.register(defaults: ["UserAgent": firefoxUA])
SDWebImageDownloader.shared().setValue(firefoxUA, forHTTPHeaderField: "User-Agent")
// Record the user agent for use by search suggestion clients.
SearchViewController.userAgent = firefoxUA
// Some sites will only serve HTML that points to .ico files.
// The FaviconFetcher is explicitly for getting high-res icons, so use the desktop user agent.
FaviconFetcher.userAgent = UserAgent.desktopUserAgent()
}
func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, for notification: UILocalNotification, completionHandler: @escaping () -> Void) {
if let actionId = identifier {
if let action = SentTabAction(rawValue: actionId) {
viewURLInNewTab(notification)
switch(action) {
case .Bookmark:
addBookmark(notification)
break
case .ReadingList:
addToReadingList(notification)
break
default:
break
}
} else {
print("ERROR: Unknown notification action received")
}
} else {
print("ERROR: Unknown notification received")
}
}
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
viewURLInNewTab(notification)
}
fileprivate func presentEmailComposerWithLogs() {
if let buildNumber = Bundle.main.object(forInfoDictionaryKey: String(kCFBundleVersionKey)) as? NSString {
let mailComposeViewController = MFMailComposeViewController()
mailComposeViewController.mailComposeDelegate = self
mailComposeViewController.setSubject("Debug Info for iOS client version v\(appVersion) (\(buildNumber))")
if DebugSettingsBundleOptions.attachLogsToDebugEmail {
do {
let logNamesAndData = try Logger.diskLogFilenamesAndData()
logNamesAndData.forEach { nameAndData in
if let data = nameAndData.1 {
mailComposeViewController.addAttachmentData(data, mimeType: "text/plain", fileName: nameAndData.0)
}
}
} catch _ {
print("Failed to retrieve logs from device")
}
}
if DebugSettingsBundleOptions.attachTabStateToDebugEmail {
if let tabStateDebugData = TabManager.tabRestorationDebugInfo().data(using: String.Encoding.utf8) {
mailComposeViewController.addAttachmentData(tabStateDebugData, mimeType: "text/plain", fileName: "tabState.txt")
}
if let tabStateData = TabManager.tabArchiveData() {
mailComposeViewController.addAttachmentData(tabStateData as Data, mimeType: "application/octet-stream", fileName: "tabsState.archive")
}
}
self.window?.rootViewController?.present(mailComposeViewController, animated: true, completion: nil)
}
}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
if let url = userActivity.webpageURL {
browserViewController.switchToTabForURLOrOpen(url)
return true
}
return false
}
fileprivate func viewURLInNewTab(_ notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String {
if let urlToOpen = URL(string: alertURL) {
browserViewController.openURLInNewTab(urlToOpen)
}
} else if let message = notification.alertBody, let url = notification.userInfo?["url"] as? String {
if UIApplication.shared.applicationState == .active {
FeedbackUI.showToastMessage(message, messageType: .info, timeInterval: 4.0, tabHandler: {[weak self] in
NotificationCenter.default.post(name: ShowBrowserViewControllerNotification, object: nil)
self?.browserViewController.openURLInNewTab(URL(string: url))
TelemetryLogger.sharedInstance.logEvent(.Notification("click", "subscription"))
})
} else {
NotificationCenter.default.post(name: ShowBrowserViewControllerNotification, object: nil)
browserViewController.initialURL = url
TelemetryLogger.sharedInstance.logEvent(.Notification("click", "subscription"))
}
}
}
fileprivate func addBookmark(_ notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String,
let title = notification.userInfo?[TabSendTitleKey] as? String {
let tabState = TabState(isPrivate: false, desktopSite: false, isBookmarked: false, url: URL(string: alertURL), title: title, favicon: nil)
browserViewController.addBookmark(tabState)
// Cliqz: comented Firefox 3D Touch code
// if #available(iOS 9, *) {
// let userData = [QuickActions.TabURLKey: alertURL,
// QuickActions.TabTitleKey: title]
// QuickActions.sharedInstance.addDynamicApplicationShortcutItemOfType(.OpenLastBookmark, withUserData: userData, toApplication: UIApplication.sharedApplication())
// }
}
}
fileprivate func addToReadingList(_ notification: UILocalNotification) {
if let alertURL = notification.userInfo?[TabSendURLKey] as? String,
let title = notification.userInfo?[TabSendTitleKey] as? String {
if let urlToOpen = URL(string: alertURL) {
NotificationCenter.default.post(name: NSNotification.Name.FSReadingListAddReadingListItem, object: self, userInfo: ["URL": urlToOpen, "Title": title])
}
}
}
// Cliqz: comented Firefox 3D Touch code
// @available(iOS 9.0, *)
// func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: Bool -> Void) {
// let handledShortCutItem = QuickActions.sharedInstance.handleShortCutItem(shortcutItem, withBrowserViewController: browserViewController)
//
// completionHandler(handledShortCutItem)
// }
}
//Util
extension AppDelegate {
func presentContollerOnTop(controller: UIViewController) {
var rootViewController = UIApplication.shared.keyWindow?.rootViewController
if let navigationController = rootViewController as? UINavigationController {
rootViewController = navigationController.viewControllers.first
}
if let tabBarController = rootViewController as? UITabBarController {
rootViewController = tabBarController.selectedViewController
}
rootViewController?.present(controller, animated: true, completion: nil)
}
}
// MARK: - Root View Controller Animations
extension AppDelegate: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController,
animationControllerFor operation: UINavigationControllerOperation,
from fromVC: UIViewController,
to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
if operation == UINavigationControllerOperation.push {
return BrowserToTrayAnimator()
} else if operation == UINavigationControllerOperation.pop {
return TrayToBrowserAnimator()
} else {
return nil
}
}
}
extension AppDelegate: TabManagerStateDelegate {
func tabManagerWillStoreTabs(_ tabs: [Tab]) {
// It is possible that not all tabs have loaded yet, so we filter out tabs with a nil URL.
let storedTabs: [RemoteTab] = tabs.flatMap( Tab.toTab )
// Don't insert into the DB immediately. We tend to contend with more important
// work like querying for top sites.
let queue = DispatchQueue.global(priority: DispatchQueue.GlobalQueuePriority.background)
queue.asyncAfter(deadline: DispatchTime.now() + Double(Int64(ProfileRemoteTabsSyncDelay * Double(NSEC_PER_MSEC))) / Double(NSEC_PER_SEC)) {
self.profile?.storeTabs(storedTabs)
}
}
}
extension AppDelegate: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
// Dismiss the view controller and start the app up
controller.dismiss(animated: true, completion: nil)
startApplication(application!, withLaunchOptions: self.launchOptions)
}
}
struct LaunchParams {
let url: URL?
let isPrivate: Bool?
}
|
mpl-2.0
|
f68a47e0c48395d7c53274bf9fd38c97
| 43.544489 | 198 | 0.672411 | 5.518592 | false | false | false | false |
MAARK/Charts
|
ChartsDemo-iOS/Swift/Demos/RadarChartViewController.swift
|
2
|
6978
|
//
// RadarChartViewController.swift
// ChartsDemo-iOS
//
// Created by Jacob Christie on 2017-07-09.
// Copyright © 2017 jc. All rights reserved.
//
import UIKit
import Charts
class RadarChartViewController: DemoBaseViewController {
@IBOutlet var chartView: RadarChartView!
let activities = ["Burger", "Steak", "Salad", "Pasta", "Pizza"]
var originalBarBgColor: UIColor!
var originalBarTintColor: UIColor!
var originalBarStyle: UIBarStyle!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = "Radar Chart"
self.options = [.toggleValues,
.toggleHighlight,
.toggleHighlightCircle,
.toggleXLabels,
.toggleYLabels,
.toggleRotate,
.toggleFilled,
.animateX,
.animateY,
.animateXY,
.spin,
.saveToGallery,
.toggleData]
chartView.delegate = self
chartView.chartDescription?.enabled = false
chartView.webLineWidth = 1
chartView.innerWebLineWidth = 1
chartView.webColor = .lightGray
chartView.innerWebColor = .lightGray
chartView.webAlpha = 1
let marker = RadarMarkerView.viewFromXib()!
marker.chartView = chartView
chartView.marker = marker
let xAxis = chartView.xAxis
xAxis.labelFont = .systemFont(ofSize: 9, weight: .light)
xAxis.xOffset = 0
xAxis.yOffset = 0
xAxis.valueFormatter = self
xAxis.labelTextColor = .white
let yAxis = chartView.yAxis
yAxis.labelFont = .systemFont(ofSize: 9, weight: .light)
yAxis.labelCount = 5
yAxis.axisMinimum = 0
yAxis.axisMaximum = 80
yAxis.drawLabelsEnabled = false
let l = chartView.legend
l.horizontalAlignment = .center
l.verticalAlignment = .top
l.orientation = .horizontal
l.drawInside = false
l.font = .systemFont(ofSize: 10, weight: .light)
l.xEntrySpace = 7
l.yEntrySpace = 5
l.textColor = .white
// chartView.legend = l
self.updateChartData()
chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4, easingOption: .easeOutBack)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
UIView.animate(withDuration: 0.15) {
let navBar = self.navigationController!.navigationBar
self.originalBarBgColor = navBar.barTintColor
self.originalBarTintColor = navBar.tintColor
self.originalBarStyle = navBar.barStyle
navBar.barTintColor = self.view.backgroundColor
navBar.tintColor = .white
navBar.barStyle = .black
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
UIView.animate(withDuration: 0.15) {
let navBar = self.navigationController!.navigationBar
navBar.barTintColor = self.originalBarBgColor
navBar.tintColor = self.originalBarTintColor
navBar.barStyle = self.originalBarStyle
}
}
override func updateChartData() {
if self.shouldHideData {
chartView.data = nil
return
}
self.setChartData()
}
func setChartData() {
let mult: UInt32 = 80
let min: UInt32 = 20
let cnt = 5
let block: (Int) -> RadarChartDataEntry = { _ in return RadarChartDataEntry(value: Double(arc4random_uniform(mult) + min))}
let entries1 = (0..<cnt).map(block)
let entries2 = (0..<cnt).map(block)
let set1 = RadarChartDataSet(entries: entries1, label: "Last Week")
set1.setColor(UIColor(red: 103/255, green: 110/255, blue: 129/255, alpha: 1))
set1.fillColor = UIColor(red: 103/255, green: 110/255, blue: 129/255, alpha: 1)
set1.drawFilledEnabled = true
set1.fillAlpha = 0.7
set1.lineWidth = 2
set1.drawHighlightCircleEnabled = true
set1.setDrawHighlightIndicators(false)
let set2 = RadarChartDataSet(entries: entries2, label: "This Week")
set2.setColor(UIColor(red: 121/255, green: 162/255, blue: 175/255, alpha: 1))
set2.fillColor = UIColor(red: 121/255, green: 162/255, blue: 175/255, alpha: 1)
set2.drawFilledEnabled = true
set2.fillAlpha = 0.7
set2.lineWidth = 2
set2.drawHighlightCircleEnabled = true
set2.setDrawHighlightIndicators(false)
let data = RadarChartData(dataSets: [set1, set2])
data.setValueFont(.systemFont(ofSize: 8, weight: .light))
data.setDrawValues(false)
data.setValueTextColor(.white)
chartView.data = data
}
override func optionTapped(_ option: Option) {
switch option {
case .toggleXLabels:
chartView.xAxis.drawLabelsEnabled = !chartView.xAxis.drawLabelsEnabled
chartView.data?.notifyDataChanged()
chartView.notifyDataSetChanged()
chartView.setNeedsDisplay()
case .toggleYLabels:
chartView.yAxis.drawLabelsEnabled = !chartView.yAxis.drawLabelsEnabled
chartView.setNeedsDisplay()
case .toggleRotate:
chartView.rotationEnabled = !chartView.rotationEnabled
case .toggleFilled:
for set in chartView.data!.dataSets as! [RadarChartDataSet] {
set.drawFilledEnabled = !set.drawFilledEnabled
}
chartView.setNeedsDisplay()
case .toggleHighlightCircle:
for set in chartView.data!.dataSets as! [RadarChartDataSet] {
set.drawHighlightCircleEnabled = !set.drawHighlightCircleEnabled
}
chartView.setNeedsDisplay()
case .animateX:
chartView.animate(xAxisDuration: 1.4)
case .animateY:
chartView.animate(yAxisDuration: 1.4)
case .animateXY:
chartView.animate(xAxisDuration: 1.4, yAxisDuration: 1.4)
case .spin:
chartView.spin(duration: 2, fromAngle: chartView.rotationAngle, toAngle: chartView.rotationAngle + 360, easingOption: .easeInCubic)
default:
super.handleOption(option, forChartView: chartView)
}
}
}
extension RadarChartViewController: IAxisValueFormatter {
func stringForValue(_ value: Double, axis: AxisBase?) -> String {
return activities[Int(value) % activities.count]
}
}
|
apache-2.0
|
28d09448ef8b483b8dd929b07faf2f19
| 33.369458 | 143 | 0.589795 | 4.972915 | false | false | false | false |
dalequi/yelpitoff
|
Demo/OAuthSwift/OAuthSwift/OAuthSwiftClient.swift
|
1
|
11192
|
//
// OAuthSwiftClient.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
var dataEncoding: NSStringEncoding = NSUTF8StringEncoding
public class OAuthSwiftClient {
private(set) public var credential: OAuthSwiftCredential
public init(consumerKey: String, consumerSecret: String) {
self.credential = OAuthSwiftCredential(consumer_key: consumerKey, consumer_secret: consumerSecret)
}
public init(consumerKey: String, consumerSecret: String, accessToken: String, accessTokenSecret: String) {
self.credential = OAuthSwiftCredential(oauth_token: accessToken, oauth_token_secret: accessTokenSecret)
self.credential.consumer_key = consumerKey
self.credential.consumer_secret = consumerSecret
}
public func get(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .GET, parameters: parameters, headers: headers, success: success, failure: failure)
}
public func post(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .POST, parameters: parameters, success: success, failure: failure)
}
public func put(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .PUT, parameters: parameters, success: success, failure: failure)
}
public func delete(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .DELETE, parameters: parameters, success: success, failure: failure)
}
public func patch(urlString: String, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.request(urlString, method: .PATCH, parameters: parameters, success: success, failure: failure)
}
public func request(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let request = makeRequest(url, method: method, parameters: parameters, headers: headers) {
request.successHandler = success
request.failureHandler = failure
request.start()
}
}
public func makeRequest(urlString: String, method: OAuthSwiftHTTPRequest.Method, parameters: [String: AnyObject] = [:], headers: [String:String]? = nil) -> OAuthSwiftHTTPRequest? {
if let url = NSURL(string: urlString) {
// Need to account for the fact that some consumers will have additional parameters on the
// querystring, including in the case of fetching a request token. Especially in the case of
// additional parameters on the request, authorize, or access token exchanges, we need to
// normalize the URL and add to the parametes collection.
var signatureUrl = url
var queryStringParameters = Dictionary<String, AnyObject>()
let urlComponents = NSURLComponents(URL: url, resolvingAgainstBaseURL: false )
if let queryItems = urlComponents?.queryItems {
for queryItem in queryItems {
let value = queryItem.value?.safeStringByRemovingPercentEncoding ?? ""
queryStringParameters.updateValue(value, forKey: queryItem.name)
}
}
// According to the OAuth1.0a spec, the url used for signing is ONLY scheme, path, and query
if(queryStringParameters.count>0)
{
urlComponents?.query = nil
// This is safe to unwrap because these just came from an NSURL
signatureUrl = urlComponents?.URL ?? url
}
let signatureParameters = parameters.join(queryStringParameters)
let request = OAuthSwiftHTTPRequest(URL: url, method: method, parameters: parameters)
var requestHeaders = self.credential.makeHeaders(signatureUrl, method: method, parameters: signatureParameters)
if let addHeaders = headers{
requestHeaders += addHeaders
}
request.headers = requestHeaders
request.dataEncoding = dataEncoding
return request
}
return nil
}
public func postImage(urlString: String, parameters: Dictionary<String, AnyObject>, image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
self.multiPartRequest(urlString, method: .POST, parameters: parameters, image: image, success: success, failure: failure)
}
func multiPartRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: Dictionary<String, AnyObject>, image: NSData, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let request = makeRequest(url, method: method, parameters: parameters) {
var parmaImage = [String: AnyObject]()
parmaImage["media"] = image
let boundary = "AS-boundary-\(arc4random())-\(arc4random())"
let type = "multipart/form-data; boundary=\(boundary)"
let body = self.multiPartBodyFromParams(parmaImage, boundary: boundary)
request.HTTPBody = body
request.headers += ["Content-Type": type] // "Content-Length": body.length.description
request.successHandler = success
request.failureHandler = failure
request.start()
}
}
public func multiPartBodyFromParams(parameters: [String: AnyObject], boundary: String) -> NSData {
let data = NSMutableData()
let prefixData = "--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
let seperData = "\r\n".dataUsingEncoding(NSUTF8StringEncoding)
for (key, value) in parameters {
var sectionData: NSData?
var sectionType: String?
var sectionFilename = ""
if key == "media" {
let multiData = value as! NSData
sectionData = multiData
sectionType = "image/jpeg"
sectionFilename = " filename=\"file\""
} else {
sectionData = "\(value)".dataUsingEncoding(NSUTF8StringEncoding)
}
data.appendData(prefixData!)
let sectionDisposition = "Content-Disposition: form-data; name=\"media\";\(sectionFilename)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(sectionDisposition!)
if let type = sectionType {
let contentType = "Content-Type: \(type)\r\n".dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(contentType!)
}
// append data
data.appendData(seperData!)
data.appendData(sectionData!)
data.appendData(seperData!)
}
data.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
return data
}
public func postMultiPartRequest(url: String, method: OAuthSwiftHTTPRequest.Method, parameters: Dictionary<String, AnyObject>, success: OAuthSwiftHTTPRequest.SuccessHandler?, failure: OAuthSwiftHTTPRequest.FailureHandler?) {
if let request = makeRequest(url, method: method, parameters: parameters) {
let boundary = "POST-boundary-\(arc4random())-\(arc4random())"
let type = "multipart/form-data; boundary=\(boundary)"
let body = self.multiDataFromObject(parameters, boundary: boundary)
request.HTTPBody = body
request.headers += ["Content-Type": type] // "Content-Length": body.length.description
request.successHandler = success
request.failureHandler = failure
request.start()
}
}
func multiDataFromObject(object: [String:AnyObject], boundary: String) -> NSData? {
let data = NSMutableData()
let prefixString = "--\(boundary)\r\n"
let prefixData = prefixString.dataUsingEncoding(NSUTF8StringEncoding)!
let seperatorString = "\r\n"
let seperatorData = seperatorString.dataUsingEncoding(NSUTF8StringEncoding)!
for (key, value) in object {
var valueData: NSData?
let valueType: String = ""
let filenameClause = ""
let stringValue = "\(value)"
valueData = stringValue.dataUsingEncoding(NSUTF8StringEncoding)!
if valueData == nil {
continue
}
data.appendData(prefixData)
let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n"
let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(contentDispositionData!)
if let type: String = valueType {
let contentTypeString = "Content-Type: \(type)\r\n"
let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)
data.appendData(contentTypeData!)
}
data.appendData(seperatorData)
data.appendData(valueData!)
data.appendData(seperatorData)
}
let endingString = "--\(boundary)--\r\n"
let endingData = endingString.dataUsingEncoding(NSUTF8StringEncoding)!
data.appendData(endingData)
return data
}
@available(*, deprecated=0.4.6, message="Because method moved to OAuthSwiftCredential!")
public class func authorizationHeaderForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, credential: OAuthSwiftCredential) -> String {
return credential.authorizationHeaderForMethod(OAuthSwiftHTTPRequest.Method(rawValue: method)!, url: url, parameters: parameters)
}
@available(*, deprecated=0.4.6, message="Because method moved to OAuthSwiftCredential!")
public class func signatureForMethod(method: String, url: NSURL, parameters: Dictionary<String, AnyObject>, credential: OAuthSwiftCredential) -> String {
return credential.signatureForMethod(OAuthSwiftHTTPRequest.Method(rawValue: method)!, url: url, parameters: parameters)
}
}
|
mit
|
f11d6edfa4ac0644bbf2f6492c9c681c
| 48.303965 | 244 | 0.654753 | 5.332063 | false | false | false | false |
adrfer/swift
|
test/NameBinding/name-binding.swift
|
2
|
6577
|
// RUN: %target-swift-frontend -parse %s -module-name themodule -enable-source-import -I %S/../decl/enum -sdk "" -verify -show-diagnostics-after-fatal
import Swift
import nonexistentimport // expected-error {{no such module 'nonexistentimport'}}
//===----------------------------------------------------------------------===//
// Test imported names
//===----------------------------------------------------------------------===//
// Imported from swift stdlib.
var importedtype : Int
// Imported from enumtest module.
import enum enumtest.unionSearchFlags
var importedunion : unionSearchFlags = .Backwards
// This shouldn't be imported from data.
var notimported : MaybeInt // expected-error {{use of undeclared type 'MaybeInt'}}
//===----------------------------------------------------------------------===//
// Name binding stress test
//===----------------------------------------------------------------------===//
var callee1 : () -> (Int,Int,Int) // Takes nothing, returns tuple.
func test_shadowing() {
// Shadow Int.
enum Int { case xyz; case abc }
// We get the shadowed version of Int.
var _ : Int = .abc
}
func unknown_member() {
var error = Swift.nonexistent_member // expected-error {{module 'Swift' has no member named 'nonexistent_member'}}
}
//===----------------------------------------------------------------------===//
// varname Processing
//===----------------------------------------------------------------------===//
var varname1 : (a : Int, b : Int)
// Not very useful, but it is allowed.
var (varname2_a, varname2_b) : (a : Int, b : Int) = varname1
func test_varname_binding() {
var c = (4, 5)
var (d, e) = (c.1, c.0)
var ((), (g1, g2), h) = ((), (e, d), e)
var (j, k, l) = callee1()
var (m, n) = callee1() // expected-error{{'(Int, Int, Int)' is not convertible to '(_, _)', tuples have a different number of elements}}
var (o, p, q, r) = callee1() // expected-error{{'(Int, Int, Int)' is not convertible to '(_, _, _, _)', tuples have a different number of elements}}
}
//===----------------------------------------------------------------------===//
// ForwardIndexType referencing of types.
//===----------------------------------------------------------------------===//
// We don't allow namebinding to look forward past a var declaration in the
// main module
var x : x_ty // expected-error {{use of undeclared type 'x_ty'}}
typealias x_ty = Int
// We allow namebinding to look forward past a function declaration (and other
// declarations which never have side-effects) in the main module
func fy() -> y_ty { return 1 }
typealias y_ty = Int
// FIXME: Should reject this!
//typealias x = x
// FIXME: Should reject this (has infinite size or is tautological depend on
// how you look at it).
enum y {
case y
case Int
}
// We don't have a typeof, but this would also be an error somehow.
//var x : typeof(x)
//===----------------------------------------------------------------------===//
// ForwardIndexType referencing of values.
//===----------------------------------------------------------------------===//
func func2() {
func3()
}
func func3() {
undefined_func() // expected-error {{use of unresolved identifier 'undefined_func'}}
}
//===----------------------------------------------------------------------===//
// Overloading
//===----------------------------------------------------------------------===//
struct a_struct { var x : Int }
infix operator *** {
associativity left
precedence 97
}
func ***(lhs: Int, rhs: Int) -> Int {
return 4
}
func ***(lhs: a_struct, rhs: a_struct) {}
func ***(lhs: a_struct, rhs: (Int) -> Int) {}
func ov_fn_result() -> Int {}
func ov_fn_result() -> Double {}
func ov_fn_result2() -> (Int) -> (Int) -> Int {}
func ov_fn_result2() -> (Int) -> (a_struct) -> Int {}
func overloadtest(x: Int) {
var _ : Int = ((ov_fn_result))()
var _ : Double = ((ov_fn_result))()
// Test overloaded operators.
let s : a_struct
4 *** 17 // Resolved to the *** operator that takes ints.
s *** s // Resolved to the *** operator that takes a_struct.
s *** {$0 + 4} // Closure obviously not a struct.
ov_fn_result2()(4)(4) // picks the ov_fn_result2 taking an Int.
ov_fn_result2()(4)(s) // picks the ov_fn_result2 taking a_struct.
}
func localtest() {
func shadowbug() {
var Foo = 10
func g() {
struct S {
// FIXME: Swap these two lines to crash our broken lookup.
typealias Foo = Int
var x : Foo
}
}
}
func scopebug() {
var Foo = 10
struct S {
typealias Foo = Int
}
Foo = 17
_ = Foo
}
func scopebug2() {
struct S1 {}
struct S2 {
var x : S1
}
}
}
func f0() -> ThisTypeDoesNotExist { return 1 } // expected-error {{use of undeclared type 'ThisTypeDoesNotExist'}}
for _ in [1] { }
//===----------------------------------------------------------------------===//
// Accessing names from our own module
//===----------------------------------------------------------------------===//
var qualifiedvalue : Int = themodule.importedtype
var qualifiedtype : themodule.x_ty = 5
prefix operator +++ {}
postfix operator +++ {}
prefix operator ++ {}
postfix operator ++ {}
prefix func +++(inout a: Int) { a += 2 }
postfix func +++(inout a: Int) { a += 2 }
var test = 0
+++test
test+++
//===----------------------------------------------------------------------===//
// Forward references to local variables.
//===----------------------------------------------------------------------===//
func forwardReference() {
x = 0 // expected-error{{use of local variable 'x' before its declaration}}
var x: Float = 0.0 // expected-note{{'x' declared here}}
}
class ForwardReference {
var x: Int = 0
func test() {
x = 0 // expected-error{{use of local variable 'x' before its declaration}}
var x: Float = 0.0 // expected-note{{'x' declared here}}
}
}
func questionablyValidForwardReference() { print(qvfrVar, terminator: ""); }; var qvfrVar: Int = 0
// FIXME: This should warn too.
print(forwardReferenceVar, terminator: ""); var forwardReferenceVar: Int = 0
// <rdar://problem/23248290> Name lookup: "Cannot convert type 'Int' to expected argument type 'Int'" while trying to initialize ivar of generic type in class scope
// https://gist.github.com/erynofwales/61768899502b7ac83c6e
struct Matrix4<T: FloatingPointType> {
static func size() -> Int {}
private var data: Int = Matrix4.size() // Ok: Matrix4<T>
init() {
data = Matrix4.size() // Ok: Matrix4<T>
}
}
|
apache-2.0
|
29086addb5e7c30ec68d8ed537834522
| 28.493274 | 164 | 0.513152 | 4.095268 | false | true | false | false |
slavapestov/swift
|
test/SILGen/function_conversion.swift
|
2
|
21316
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
// Check SILGen against various FunctionConversionExprs emitted by Sema.
// ==== Representation conversions
// CHECK-LABEL: sil hidden @_TF19function_conversion7cToFuncFcSiSiFSiSi : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @callee_owned (Int) -> Int
// CHECK: [[THUNK:%.*]] = function_ref @_TTRXFtCc_dSi_dSi_XFo_dSi_dSi_
// CHECK: [[FUNC:%.*]] = partial_apply [[THUNK]](%0)
// CHECK: return [[FUNC]]
func cToFunc(arg: @convention(c) Int -> Int) -> Int -> Int {
return arg
}
// CHECK-LABEL: sil hidden @_TF19function_conversion8cToBlockFcSiSibSiSi : $@convention(thin) (@convention(c) (Int) -> Int) -> @owned @convention(block) (Int) -> Int
// CHECK: [[BLOCK_STORAGE:%.*]] = alloc_stack $@block_storage
// CHECK: [[BLOCK:%.*]] = init_block_storage_header [[BLOCK_STORAGE]]
// CHECK: [[COPY:%.*]] = copy_block [[BLOCK]] : $@convention(block) (Int) -> Int
// CHECK: return [[COPY]]
func cToBlock(arg: @convention(c) Int -> Int) -> @convention(block) Int -> Int {
return arg
}
// ==== Throws variance
// CHECK-LABEL: sil hidden @_TF19function_conversion12funcToThrowsFFT_T_FzT_T_ : $@convention(thin) (@owned @callee_owned () -> ()) -> @owned @callee_owned () -> @error ErrorType
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@callee_owned () -> () to $@callee_owned () -> @error ErrorType
// CHECK: return [[FUNC]]
func funcToThrows(x: () -> ()) -> () throws -> () {
return x
}
// CHECK-LABEL: sil hidden @_TF19function_conversion12thinToThrowsFXfT_T_XfzT_T_ : $@convention(thin) (@convention(thin) () -> ()) -> @convention(thin) () -> @error ErrorType
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@convention(thin) () -> () to $@convention(thin) () -> @error ErrorType
// CHECK: return [[FUNC]] : $@convention(thin) () -> @error ErrorType
func thinToThrows(x: @convention(thin) () -> ()) -> @convention(thin) () throws -> () {
return x
}
// FIXME: triggers an assert because we always do a thin to thick conversion on DeclRefExprs
/*
func thinFunc() {}
func thinToThrows() {
let _: @convention(thin) () -> () = thinFunc
}
*/
// ==== Class downcasts and upcasts
class Feral {}
class Domesticated : Feral {}
// CHECK-LABEL: sil hidden @_TF19function_conversion12funcToUpcastFFT_CS_12DomesticatedFT_CS_5Feral : $@convention(thin) (@owned @callee_owned () -> @owned Domesticated) -> @owned @callee_owned () -> @owned Feral
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@callee_owned () -> @owned Domesticated to $@callee_owned () -> @owned Feral
// CHECK: return [[FUNC]]
func funcToUpcast(x: () -> Domesticated) -> () -> Feral {
return x
}
// CHECK-LABEL: sil hidden @_TF19function_conversion12funcToUpcastFFCS_5FeralT_FCS_12DomesticatedT_ : $@convention(thin) (@owned @callee_owned (@owned Feral) -> ()) -> @owned @callee_owned (@owned Domesticated) -> ()
// CHECK: [[FUNC:%.*]] = convert_function %0 : $@callee_owned (@owned Feral) -> () to $@callee_owned (@owned Domesticated) -> () // user: %3
// CHECK: return [[FUNC]]
func funcToUpcast(x: Feral -> ()) -> Domesticated -> () {
return x
}
// ==== Optionals
struct Trivial {
let n: Int8
}
class C {
let n: Int8
init(n: Int8) {
self.n = n
}
}
struct Loadable {
let c: C
var n: Int8 {
return c.n
}
init(n: Int8) {
c = C(n: n)
}
}
struct AddrOnly {
let a: Any
var n: Int8 {
return a as! Int8
}
init(n: Int8) {
a = n
}
}
// CHECK-LABEL: sil hidden @_TF19function_conversion19convOptionalTrivialFFGSqVS_7Trivial_S0_T_
func convOptionalTrivial(t1: Trivial? -> Trivial) {
// CHECK: function_ref @_TTRXFo_dGSqV19function_conversion7Trivial__dS0__XFo_dS0__dGSqS0___
// CHECK: partial_apply
let _: Trivial -> Trivial? = t1
// CHECK: function_ref @_TTRXFo_dGSqV19function_conversion7Trivial__dS0__XFo_dGSQS0___dGSqS0___
// CHECK: partial_apply
let _: Trivial! -> Trivial? = t1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqV19function_conversion7Trivial__dS0__XFo_dS0__dGSqS0___ : $@convention(thin) (Trivial, @owned @callee_owned (Optional<Trivial>) -> Trivial) -> Optional<Trivial>
// CHECK: enum $Optional<Trivial>
// CHECK-NEXT: apply %1(%2)
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqV19function_conversion7Trivial__dS0__XFo_dGSQS0___dGSqS0___ : $@convention(thin) (ImplicitlyUnwrappedOptional<Trivial>, @owned @callee_owned (Optional<Trivial>) -> Trivial) -> Optional<Trivial>
// CHECK: unchecked_trivial_bit_cast %0 : $ImplicitlyUnwrappedOptional<Trivial> to $Optional<Trivial>
// CHECK-NEXT: apply %1(%2)
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_TF19function_conversion20convOptionalLoadableFFGSqVS_8Loadable_S0_T_
func convOptionalLoadable(l1: Loadable? -> Loadable) {
// CHECK: function_ref @_TTRXFo_oGSqV19function_conversion8Loadable__oS0__XFo_oS0__oGSqS0___
// CHECK: partial_apply
let _: Loadable -> Loadable? = l1
// CHECK: function_ref @_TTRXFo_oGSqV19function_conversion8Loadable__oS0__XFo_oGSQS0___oGSqS0___
// CHECK: partial_apply
let _: Loadable! -> Loadable? = l1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_oGSqV19function_conversion8Loadable__oS0__XFo_oGSQS0___oGSqS0___ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Loadable>, @owned @callee_owned (@owned Optional<Loadable>) -> @owned Loadable) -> @owned Optional<Loadable>
// CHECK: unchecked_bitwise_cast %0 : $ImplicitlyUnwrappedOptional<Loadable> to $Optional<Loadable>
// CHECK-NEXT: apply %1(%2)
// CHECK-NEXT: enum $Optional<Loadable>
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_TF19function_conversion20convOptionalAddrOnlyFFGSqVS_8AddrOnly_S0_T_
func convOptionalAddrOnly(a1: AddrOnly? -> AddrOnly) {
// CHECK: function_ref @_TTRXFo_iGSqV19function_conversion8AddrOnly__iS0__XFo_iGSqS0___iGSqS0___
// CHECK: partial_apply
let _: AddrOnly? -> AddrOnly? = a1
// CHECK: function_ref @_TTRXFo_iGSqV19function_conversion8AddrOnly__iS0__XFo_iGSQS0___iGSqS0___
// CHECK: partial_apply
let _: AddrOnly! -> AddrOnly? = a1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iGSqV19function_conversion8AddrOnly__iS0__XFo_iGSqS0___iGSqS0___ : $@convention(thin) (@out Optional<AddrOnly>, @in Optional<AddrOnly>, @owned @callee_owned (@out AddrOnly, @in Optional<AddrOnly>) -> ()) -> ()
// CHECK: alloc_stack $AddrOnly
// CHECK-NEXT: apply %2(%3, %1)
// CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: dealloc_stack {{.*}} : $*AddrOnly
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iGSqV19function_conversion8AddrOnly__iS0__XFo_iGSQS0___iGSqS0___ : $@convention(thin) (@out Optional<AddrOnly>, @in ImplicitlyUnwrappedOptional<AddrOnly>, @owned @callee_owned (@out AddrOnly, @in Optional<AddrOnly>) -> ()) -> ()
// CHECK: alloc_stack $Optional<AddrOnly>
// CHECK-NEXT: unchecked_addr_cast %1 : $*ImplicitlyUnwrappedOptional<AddrOnly> to $*Optional<AddrOnly>
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*Optional<AddrOnly>
// CHECK-NEXT: alloc_stack $AddrOnly
// CHECK-NEXT: apply %2(%6, %3)
// CHECK-NEXT: init_enum_data_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}} : $*AddrOnly
// CHECK-NEXT: inject_enum_addr %0 : $*Optional<AddrOnly>
// CHECK-NEXT: dealloc_stack {{.*}} : $*AddrOnly
// CHECK-NEXT: dealloc_stack {{.*}} : $*Optional<AddrOnly>
// CHECK-NEXT: return
// ==== Existentials
protocol Q {
var n: Int8 { get }
}
protocol P : Q {}
extension Trivial : P {}
extension Loadable : P {}
extension AddrOnly : P {}
// CHECK-LABEL: sil hidden @_TF19function_conversion22convExistentialTrivialFTFPS_1Q_VS_7Trivial2t3FGSqPS0___S1__T_
func convExistentialTrivial(t2: Q -> Trivial, t3: Q? -> Trivial) {
// CHECK: function_ref @_TTRXFo_iP19function_conversion1Q__dVS_7Trivial_XFo_dS1__iPS_1P__
// CHECK: partial_apply
let _: Trivial -> P = t2
// CHECK: function_ref @_TTRXFo_iGSqP19function_conversion1Q___dVS_7Trivial_XFo_dGSqS1___iPS_1P__
// CHECK: partial_apply
let _: Trivial? -> P = t3
// CHECK: function_ref @_TTRXFo_iP19function_conversion1Q__dVS_7Trivial_XFo_iPS_1P__iPS2___
// CHECK: partial_apply
let _: P -> P = t2
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP19function_conversion1Q__dVS_7Trivial_XFo_dS1__iPS_1P__ : $@convention(thin) (@out P, Trivial, @owned @callee_owned (@in Q) -> Trivial) -> ()
// CHECK: alloc_stack $Q
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK-NEXT: apply
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iGSqP19function_conversion1Q___dVS_7Trivial_XFo_dGSqS1___iPS_1P__
// CHECK: select_enum
// CHECK: cond_br
// CHECK: bb1:
// CHECK: unchecked_enum_data
// CHECK: init_existential_addr
// CHECK: init_enum_data_addr
// CHECK: copy_addr
// CHECK: inject_enum_addr
// CHECK: bb2:
// CHECK: inject_enum_addr
// CHECK: bb3:
// CHECK: apply
// CHECK: init_existential_addr
// CHECK: store
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP19function_conversion1Q__dVS_7Trivial_XFo_iPS_1P__iPS2___ : $@convention(thin) (@out P, @in P, @owned @callee_owned (@in Q) -> Trivial) -> ()
// CHECK: alloc_stack $Q
// CHECK-NEXT: open_existential_addr %1 : $*P
// CHECK-NEXT: init_existential_addr %3 : $*Q
// CHECK-NEXT: copy_addr [take] {{.*}} to [initialization] {{.*}}
// CHECK-NEXT: apply
// CHECK-NEXT: init_existential_addr
// CHECK-NEXT: store
// CHECK: deinit_existential_addr
// CHECK: return
// ==== Existential metatypes
// CHECK-LABEL: sil hidden @_TF19function_conversion23convExistentialMetatypeFFGSqPMPS_1Q__MVS_7TrivialT_
func convExistentialMetatype(em: Q.Type? -> Trivial.Type) {
// CHECK: function_ref @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dXMtS1__dXPMTPS_1P__
// CHECK: partial_apply
let _: Trivial.Type -> P.Type = em
// CHECK: function_ref @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dGSqMS1___dXPMTPS_1P__
// CHECK: partial_apply
let _: Trivial.Type? -> P.Type = em
// CHECK: function_ref @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dXPMTPS_1P__dXPMTPS2___
// CHECK: partial_apply
let _: P.Type -> P.Type = em
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dXMtS1__dXPMTPS_1P__ : $@convention(thin) (@thin Trivial.Type, @owned @callee_owned (Optional<Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype %2 : $@thick Trivial.Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<Q.Type>
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dGSqMS1___dXPMTPS_1P__ : $@convention(thin) (Optional<Trivial.Type>, @owned @callee_owned (Optional<Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: select_enum %0 : $Optional<Trivial.Type>
// CHECK-NEXT: cond_br
// CHECK: bb1:
// CHECK-NEXT: unchecked_enum_data %0 : $Optional<Trivial.Type>
// CHECK-NEXT: metatype $@thin Trivial.Type
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<Q.Type>
// CHECK: bb2:
// CHECK-NEXT: enum $Optional<Q.Type>
// CHECK: bb3({{.*}}):
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqPMP19function_conversion1Q___dXMtVS_7Trivial_XFo_dXPMTPS_1P__dXPMTPS2___ : $@convention(thin) (@thick P.Type, @owned @callee_owned (Optional<Q.Type>) -> @thin Trivial.Type) -> @thick P.Type
// CHECK: open_existential_metatype %0 : $@thick P.Type to $@thick (@opened({{.*}}) P).Type
// CHECK-NEXT: init_existential_metatype %2 : $@thick (@opened({{.*}}) P).Type, $@thick Q.Type
// CHECK-NEXT: enum $Optional<Q.Type>
// CHECK-NEXT: apply
// CHECK-NEXT: metatype $@thick Trivial.Type
// CHECK-NEXT: init_existential_metatype {{.*}} : $@thick Trivial.Type, $@thick P.Type
// CHECK-NEXT: return
// ==== Class metatype upcasts
class Parent {}
class Child : Parent {}
// Note: we add a Trivial => Trivial? conversion here to force a thunk
// to be generated
// CHECK-LABEL: sil hidden @_TF19function_conversion18convUpcastMetatypeFTFTMCS_6ParentGSqVS_7Trivial__MCS_5Child2c5FTGSqMS0__GSqS1___MS2__T_
func convUpcastMetatype(c4: (Parent.Type, Trivial?) -> Child.Type,
c5: (Parent.Type?, Trivial?) -> Child.Type) {
// CHECK: function_ref @_TTRXFo_dXMTC19function_conversion6ParentdGSqVS_7Trivial__dXMTCS_5Child_XFo_dXMTS2_dS1__dXMTS0__
// CHECK: partial_apply
let _: (Child.Type, Trivial) -> Parent.Type = c4
// CHECK: function_ref @_TTRXFo_dGSqMC19function_conversion6Parent_dGSqVS_7Trivial__dXMTCS_5Child_XFo_dXMTS2_dS1__dXMTS0__
// CHECK: partial_apply
let _: (Child.Type, Trivial) -> Parent.Type = c5
// CHECK: function_ref @_TTRXFo_dGSqMC19function_conversion6Parent_dGSqVS_7Trivial__dXMTCS_5Child_XFo_dGSqMS2__dS1__dGSqMS0___
// CHECK: partial_apply
let _: (Child.Type?, Trivial) -> Parent.Type? = c5
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dXMTC19function_conversion6ParentdGSqVS_7Trivial__dXMTCS_5Child_XFo_dXMTS2_dS1__dXMTS0__ : $@convention(thin) (@thick Child.Type, Trivial, @owned @callee_owned (@thick Parent.Type, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type
// CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqMC19function_conversion6Parent_dGSqVS_7Trivial__dXMTCS_5Child_XFo_dXMTS2_dS1__dXMTS0__ : $@convention(thin) (@thick Child.Type, Trivial, @owned @callee_owned (Optional<Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> @thick Parent.Type
// CHECK: upcast %0 : $@thick Child.Type to $@thick Parent.Type
// CHECK: enum $Optional<Parent.Type>
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqMC19function_conversion6Parent_dGSqVS_7Trivial__dXMTCS_5Child_XFo_dGSqMS2__dS1__dGSqMS0___ : $@convention(thin) (Optional<Child.Type>, Trivial, @owned @callee_owned (Optional<Parent.Type>, Optional<Trivial>) -> @thick Child.Type) -> Optional<Parent.Type>
// CHECK: unchecked_trivial_bit_cast %0 : $Optional<Child.Type> to $Optional<Parent.Type>
// CHECK: apply
// CHECK: upcast {{.*}} : $@thick Child.Type to $@thick Parent.Type
// CHECK: enum $Optional<Parent.Type>
// CHECK: return
// ==== Function to existential -- make sure we maximally abstract it
// CHECK-LABEL: sil hidden @_TF19function_conversion19convFuncExistentialFFP_FSiSiT_ : $@convention(thin) (@owned @callee_owned (@in protocol<>) -> @owned @callee_owned (Int) -> Int) -> ()
func convFuncExistential(f1: Any -> Int -> Int) {
// CHECK: function_ref @_TTRXFo_iP__oXFo_dSi_dSi__XFo_oXFo_dSi_dSi__iP__
// CHECK: partial_apply %3(%0)
let _: (Int -> Int) -> Any = f1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP__oXFo_dSi_dSi__XFo_oXFo_dSi_dSi__iP__ : $@convention(thin) (@out protocol<>, @owned @callee_owned (Int) -> Int, @owned @callee_owned (@in protocol<>) -> @owned @callee_owned (Int) -> Int) -> ()
// CHECK: alloc_stack $protocol<>
// CHECK: function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK-NEXT: partial_apply
// CHECK-NEXT: init_existential_addr %3 : $*protocol<>, $Int -> Int
// CHECK-NEXT: store
// CHECK-NEXT: apply
// CHECK: function_ref @_TTRXFo_dSi_dSi_XFo_iSi_iSi_
// CHECK-NEXT: partial_apply
// CHECK-NEXT: init_existential_addr %0 : $*protocol<>, $Int -> Int
// CHECK-NEXT: store {{.*}} to {{.*}} : $*@callee_owned (@out Int, @in Int) -> ()
// CHECK: return
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dSi_dSi_XFo_iSi_iSi_ : $@convention(thin) (@out Int, @in Int, @owned @callee_owned (Int) -> Int) -> ()
// CHECK: load %1 : $*Int
// CHECK-NEXT: apply %2(%3)
// CHECK-NEXT: store {{.*}} to %0
// CHECK: return
// ==== Class-bound archetype upcast
// CHECK-LABEL: sil hidden @_TF19function_conversion29convClassBoundArchetypeUpcast
func convClassBoundArchetypeUpcast<T : Parent>(f1: Parent -> (T, Trivial)) {
// CHECK: function_ref @_TTRGRxC19function_conversion6ParentrXFo_oS0__oTxVS_7Trivial__XFo_ox_oTS0_GSqS1____
// CHECK: partial_apply
let _: T -> (Parent, Trivial?) = f1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRGRxC19function_conversion6ParentrXFo_oS0__oTxVS_7Trivial__XFo_ox_oTS0_GSqS1____ : $@convention(thin) <T where T : Parent> (@owned T, @owned @callee_owned (@owned Parent) -> @owned (T, Trivial)) -> @owned (Parent, Optional<Trivial>)
// CHECK: upcast %0 : $T to $Parent
// CHECK-NEXT: apply
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: upcast {{.*}} : $T to $Parent
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_TF19function_conversion37convClassBoundMetatypeArchetypeUpcast
func convClassBoundMetatypeArchetypeUpcast<T : Parent>(f1: Parent.Type -> (T.Type, Trivial)) {
// CHECK: function_ref @_TTRGRxC19function_conversion6ParentrXFo_dXMTS0__dTXMTxVS_7Trivial__XFo_dXMTx_dTXMTS0_GSqS1____
// CHECK: partial_apply
let _: T.Type -> (Parent.Type, Trivial?) = f1
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRGRxC19function_conversion6ParentrXFo_dXMTS0__dTXMTxVS_7Trivial__XFo_dXMTx_dTXMTS0_GSqS1____ : $@convention(thin) <T where T : Parent> (@thick T.Type, @owned @callee_owned (@thick Parent.Type) -> (@thick T.Type, Trivial)) -> (@thick Parent.Type, Optional<Trivial>)
// CHECK: upcast %0 : $@thick T.Type to $@thick Parent.Type
// CHECK-NEXT: apply
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: tuple_extract
// CHECK-NEXT: upcast {{.*}} : $@thick T.Type to $@thick Parent.Type
// CHECK-NEXT: enum $Optional<Trivial>
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// ==== Make sure we destructure one-element tuples
// CHECK-LABEL: sil hidden @_TF19function_conversion15convTupleScalarFTFPS_1Q_T_2f2FT6parentPS0___T_2f3FT5tupleGSqTSiSi___T__T_
// CHECK: function_ref @_TTRXFo_iP19function_conversion1Q__dT__XFo_iPS_1P__dT__
// CHECK: function_ref @_TTRXFo_iP19function_conversion1Q__dT__XFo_iPS_1P__dT__
// CHECK: function_ref @_TTRXFo_dGSqTSiSi___dT__XFo_dSidSi_dT__
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_iP19function_conversion1Q__dT__XFo_iPS_1P__dT__ : $@convention(thin) (@in P, @owned @callee_owned (@in Q) -> ()) -> ()
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRXFo_dGSqTSiSi___dT__XFo_dSidSi_dT__ : $@convention(thin) (Int, Int, @owned @callee_owned (Optional<(Int, Int)>) -> ()) -> ()
func convTupleScalar(f1: Q -> (),
f2: (parent: Q) -> (),
f3: (tuple: (Int, Int)?) -> ()) {
let _: (parent: P) -> () = f1
let _: P -> () = f2
let _: (Int, Int) -> () = f3
}
// CHECK-LABEL: sil hidden @_TF19function_conversion21convTupleScalarOpaqueurFFt4argsGSax__T_GSqFt4argsGSax__T__
// CHECK: function_ref @_TTRGrXFo_oGSax__dT__XFo_it4argsGSax___iT__
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_TTRGrXFo_oGSax__dT__XFo_it4argsGSax___iT__ : $@convention(thin) <T> (@out (), @in (args: T...), @owned @callee_owned (@owned Array<T>) -> ()) -> ()
func convTupleScalarOpaque<T>(f: (args: T...) -> ()) -> ((args: T...) -> ())? {
return f
}
|
apache-2.0
|
a95ac3d832d2b271cbffd32c07756bc1
| 48.687646 | 331 | 0.65045 | 3.20686 | false | false | false | false |
OlegKetrar/Tools
|
Sources/Tools/UIKit/Components/Button.swift
|
1
|
3135
|
//
// Button.swift
// ToolsUIKit
//
// Created by Oleg Ketrar on 04.07.17.
// Copyright © 2017 Oleg Ketrar. All rights reserved.
//
import Foundation
import UIKit
// TODO: refactor
/// `Button` with animated preloader.
/// Use to notify about performing async work.
/// `Button` use `disabled` state to show preloader, do not set any parameters to `disabled` state
@objc(ToolsButton)
public final class Button: UIButton {
private lazy var preloader: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(style: .white)
indicator.color = self.preloaderColor
indicator.frame = .zero
indicator.hidesWhenStopped = true
return indicator
}()
@IBInspectable
public var preloaderColor: UIColor = UIColor.white {
didSet { preloader.color = preloaderColor }
}
/// Should hide button image while preloader active.
/// Default `true`.
public var shouldAffectImage: Bool = true
override public init(frame: CGRect) {
super.init(frame: frame)
defaultConfiguring()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultConfiguring()
}
private func defaultConfiguring() {
addSubview(preloader)
setAttributedTitle(NSAttributedString(string: "", attributes: nil), for: .disabled)
setTitle("", for: .disabled)
}
deinit {
preloader.removeFromSuperview()
}
override public func layoutSubviews() {
super.layoutSubviews()
preloader.sizeToFit()
preloader.frame = CGRect(
x: 0.5 * (bounds.width - preloader.bounds.width),
y: 0.5 * (bounds.height - preloader.bounds.height),
width: preloader.bounds.width,
height: preloader.bounds.height)
}
/// Show animated preloader instead of button title.
public func startPreloader(_ start: Bool = true) {
guard isEnabled == start else { return }
if start {
if shouldAffectImage,
let normalImage = image(for: .normal) {
setImage(UIImage(color: .clear, size: normalImage.size), for: .disabled)
}
preloader.startAnimating()
isEnabled = false
isSelected = false
} else {
preloader.stopAnimating()
isEnabled = true
}
}
/// Hide preloader and show normal button title.
public func stopPreloader() {
startPreloader(false)
}
/// Do async work with preloader.
/// - parameter activity: Work closure to be executed (must call closure parameter when finished).
/// ```
/// let button = Button.init(frame: .zero)
/// button.start(activity: { (onCompletion) in
/// // do some async work
///
/// // call when work completed
/// onCompletion()
/// })
/// ```
public func start(activity: @escaping (@escaping () -> Void) -> Void) {
startPreloader()
activity { [weak self] in
DispatchQueue.main.async { self?.stopPreloader() }
}
}
}
|
mit
|
585ccc45ebd3013047e2b25874c4dcda
| 27.234234 | 102 | 0.606892 | 4.522367 | false | false | false | false |
YMXian/Deliria
|
Deliria/UIKit/UIColor/UIColor+Utils.swift
|
1
|
1134
|
//
// UIColor+Utils.swift
// Deliria
//
// Created by Yanke Guo on 16/2/9.
// Copyright © 2016年 JuXian(Beijing) Technology Co., Ltd. All rights reserved.
//
import UIKit
extension UIColor {
/**
Create a image from current color and size
- parameter size: size
- returns: image
*/
public func toImage(_ size: CGSize = [1, 1]) -> UIImage {
return UIImage.imageWithColor(self, size: size)
}
/// Get RGBA as Tuple, in CGFloat 0.0 ~ 1.0
public var RGBA: (CGFloat, CGFloat, CGFloat, CGFloat) {
var r: CGFloat = 0, g: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return (r, g, b, a)
}
/// Get HSBA as Tuple, in CGFloat 0.0 ~ 1.0
public var HSBA: (CGFloat, CGFloat, CGFloat, CGFloat) {
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
self.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
return (h, s, b, a)
}
/// Get White/Alpha as Tuple, in CGFloat 0.0 ~ 1.0
public var WA: (CGFloat, CGFloat) {
var w: CGFloat = 0, a: CGFloat = 0
self.getWhite(&w, alpha: &a)
return (w, a)
}
}
|
mit
|
d381cf20ecc8a638045bb6c33805d795
| 24.133333 | 79 | 0.600354 | 3.040323 | false | false | false | false |
natecook1000/swift
|
test/Interpreter/builtin_bridge_object.swift
|
3
|
5110
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -parse-stdlib %s -o %t/a.out
// RUN: %target-codesign %t/a.out
// RUN: %target-run %t/a.out | %FileCheck %s
// REQUIRES: executable_test
// FIXME: rdar://problem/19648117 Needs splitting objc parts out
// XFAIL: linux
import Swift
import SwiftShims
class C {
deinit { print("deallocated") }
}
#if arch(i386) || arch(arm)
// We have no ObjC tagged pointers, and two low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0003
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#elseif arch(x86_64)
// We have ObjC tagged pointers in the lowest and highest bit
let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0006
let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0001
#elseif arch(arm64)
// We have ObjC tagged pointers in the highest bit
let NATIVE_SPARE_BITS: UInt = 0x7F00_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0x8000_0000_0000_0000
#elseif arch(powerpc64) || arch(powerpc64le)
// We have no ObjC tagged pointers, and three low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#elseif arch(s390x)
// We have no ObjC tagged pointers, and three low spare bits due to alignment.
let NATIVE_SPARE_BITS: UInt = 0x0000_0000_0000_0007
let OBJC_TAGGED_POINTER_BITS: UInt = 0
#endif
func bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
func nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return bitPattern(x) & NATIVE_SPARE_BITS
}
// Try without any bits set.
if true {
let x = C()
let bo = Builtin.castToBridgeObject(x, 0._builtinWordValue)
let bo2 = bo
let x1: C = Builtin.castReferenceFromBridgeObject(bo)
let x2: C = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
print(nonPointerBits(bo) == 0)
// CHECK-NEXT: true
var bo3 = Builtin.castToBridgeObject(C(), 0._builtinWordValue)
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: true
let bo4 = bo3
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
_fixLifetime(bo4)
}
// CHECK-NEXT: deallocated
// CHECK-NEXT: deallocated
// Try with all spare bits set.
if true {
let x = C()
let bo = Builtin.castToBridgeObject(x, NATIVE_SPARE_BITS._builtinWordValue)
let bo2 = bo
let x1: C = Builtin.castReferenceFromBridgeObject(bo)
let x2: C = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
print(nonPointerBits(bo) == NATIVE_SPARE_BITS)
// CHECK-NEXT: true
var bo3 = Builtin.castToBridgeObject(C(), NATIVE_SPARE_BITS._builtinWordValue)
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: true
let bo4 = bo3
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
_fixLifetime(bo4)
}
// CHECK-NEXT: deallocated
// CHECK-NEXT: deallocated
import Foundation
func nonNativeBridgeObject(_ o: AnyObject) -> Builtin.BridgeObject {
let tagged = ((Builtin.reinterpretCast(o) as UInt) & OBJC_TAGGED_POINTER_BITS) != 0
return Builtin.castToBridgeObject(
o, tagged ? 0._builtinWordValue : NATIVE_SPARE_BITS._builtinWordValue)
}
// Try with a (probably) tagged pointer. No bits may be masked into a
// non-native object.
if true {
let x = NSNumber(value: 22)
let bo = nonNativeBridgeObject(x)
let bo2 = bo
let x1: NSNumber = Builtin.castReferenceFromBridgeObject(bo)
let x2: NSNumber = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
var bo3 = nonNativeBridgeObject(NSNumber(value: 22))
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
}
var unTaggedString: NSString {
return NSString(format: "A long string that won't fit in a tagged pointer")
}
// Try with an un-tagged pointer.
if true {
let x = unTaggedString
let bo = nonNativeBridgeObject(x)
let bo2 = bo
let x1: NSString = Builtin.castReferenceFromBridgeObject(bo)
let x2: NSString = Builtin.castReferenceFromBridgeObject(bo2)
// CHECK-NEXT: true
print(x === x1)
// CHECK-NEXT: true
print(x === x2)
var bo3 = nonNativeBridgeObject(unTaggedString)
print(_getBool(Builtin.isUnique(&bo3)))
// CHECK-NEXT: false
_fixLifetime(bo3)
}
func hitOptionalGenerically<T>(_ x: T?) {
switch x {
case .some:
print("some")
case .none:
print("none")
}
}
func hitOptionalSpecifically(_ x: Builtin.BridgeObject?) {
switch x {
case .some:
print("some")
case .none:
print("none")
}
}
if true {
// CHECK-NEXT: true
print(MemoryLayout<Optional<Builtin.BridgeObject>>.size
== MemoryLayout<Builtin.BridgeObject>.size)
var bo: Builtin.BridgeObject?
// CHECK-NEXT: none
hitOptionalSpecifically(bo)
// CHECK-NEXT: none
hitOptionalGenerically(bo)
bo = Builtin.castToBridgeObject(C(), 0._builtinWordValue)
// CHECK-NEXT: some
hitOptionalSpecifically(bo)
// CHECK: some
hitOptionalGenerically(bo)
}
|
apache-2.0
|
5196f9471d08db7c394a0e978fd3036b
| 24.808081 | 85 | 0.700978 | 3.296774 | false | false | false | false |
turingcorp/gattaca
|
UnitTests/Model/Session/TMSessionLocation.swift
|
1
|
11801
|
import XCTest
@testable import gattaca
class TMSessionLocation:XCTestCase
{
private var coreData:Database?
private let kUserId:String = "johnnyTest"
private let kCountry:String = "bananaRepublic"
private let kOtherCountry:String = "coffeeRepublic"
private let kLatitude:Double = 1
private let kLongitude:Double = 2
private let kWaitExpectation:TimeInterval = 3
override func setUp()
{
super.setUp()
let bundle:Bundle = Bundle(for:TMSessionLocation.self)
coreData = Database(bundle:bundle)
}
//MARK: private
private func createUser(session:MSession)
{
session.userId = kUserId
session.country = kCountry
session.status = DSession.Status.active
}
private func createUserCoreData(
session:MSession,
completion:@escaping(() -> ()))
{
guard
let coreData:Database = self.coreData
else
{
return
}
coreData.create
{ [weak self] (user:DSession) in
user.initialValues()
user.userId = self?.kUserId
user.country = self?.kCountry
session.updateSession(session:user)
completion()
}
}
private func addLocation(
session:MSession,
firebase:FDatabase,
completion:@escaping(() -> ()))
{
let countries:FDatabaseCountries = FDatabaseCountries()
let country:FDatabaseCountriesItem = FDatabaseCountriesItem(
countries:countries,
identifier:kCountry)
guard
let userId:String = session.userId,
let user:FDatabaseCountriesItemUser = FDatabaseCountriesItemUser(
country:country,
identifier:userId,
latitude:kLatitude,
longitude:kLongitude)
else
{
return
}
firebase.update(model:user)
completion()
}
private func getCountryUser(
userId:String,
country:String,
firebase:FDatabase,
completion:@escaping((FDatabaseCountriesItemUser?) -> ()))
{
let countries:FDatabaseCountries = FDatabaseCountries()
let country:FDatabaseCountriesItem = FDatabaseCountriesItem(
countries:countries,
identifier:country)
firebase.load(parent:country, identifier:userId)
{ (user:FDatabaseCountriesItemUser?) in
completion(user)
}
}
private func getUserLocation(
userId:String,
firebase:FDatabase,
completion:@escaping((FDatabaseUsersItemLocation?) -> ()))
{
let users:FDatabaseUsers = FDatabaseUsers()
let user:FDatabaseUsersItem = FDatabaseUsersItem(
users:users)
user.identifier = userId
firebase.load(
parent:user,
identifier:FDatabaseUsersItem.kKeyLocation)
{ (location:FDatabaseUsersItemLocation?) in
completion(location)
}
}
private func createUserAtLocation(
completion:@escaping((MSession, FDatabase) -> ()))
{
let session:MSession = MSession()
let firebase:FDatabase = FDatabase()
createUser(session:session)
addLocation(
session:session,
firebase:firebase)
{
completion(session, firebase)
}
}
private func createFirebaseUser(
session:MSession,
firebase:FDatabase)
{
let users:FDatabaseUsers = FDatabaseUsers()
let user:FDatabaseUsersItem = FDatabaseUsersItem(
users:users)
guard
let userJson:Any = user.json
else
{
return
}
let userId:String = firebase.create(
parent:users,
data:userJson)
session.userId = userId
}
//MARK: internal
func testSyncLocation()
{
guard
let coreData:Database = self.coreData
else
{
return
}
let syncExpectation:XCTestExpectation = expectation(
description:"sync location")
let session:MSession = MSession()
session.syncLocation(
coreData:coreData,
latitude:kLatitude,
longitude:kLongitude,
country:kCountry)
{
syncExpectation.fulfill()
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
XCTAssertNotNil(
session.country,
"location not syncing")
}
}
func testRemovePreviousLocationDifferent()
{
var firebaseCountryUser:FDatabaseCountriesItemUser?
let firstCountry:String = kCountry
let newCountry:String = kOtherCountry
let removeExpectation:XCTestExpectation = expectation(
description:"remove user from country")
createUserAtLocation
{ [weak self] (session:MSession, firebase:FDatabase) in
guard
let userId:String = session.userId
else
{
return
}
session.removePreviousLocation(
newCountry:newCountry,
firebase:firebase)
self?.getCountryUser(
userId:userId,
country:firstCountry,
firebase:firebase)
{ (countryUser:FDatabaseCountriesItemUser?) in
firebaseCountryUser = countryUser
removeExpectation.fulfill()
}
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
XCTAssertNil(
firebaseCountryUser,
"country user should be nil")
}
}
func testRemovePreviousLocationSame()
{
var firebaseCountryUser:FDatabaseCountriesItemUser?
let country:String = kCountry
let removeExpectation:XCTestExpectation = expectation(
description:"remove user from country")
createUserAtLocation
{ [weak self] (session:MSession, firebase:FDatabase) in
guard
let userId:String = session.userId
else
{
return
}
session.removePreviousLocation(
newCountry:country,
firebase:firebase)
self?.getCountryUser(
userId:userId,
country:country,
firebase:firebase)
{ (countryUser:FDatabaseCountriesItemUser?) in
firebaseCountryUser = countryUser
removeExpectation.fulfill()
}
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
XCTAssertNotNil(
firebaseCountryUser,
"country user should not be removed")
}
}
func testCoreDataLocation()
{
let session:MSession = MSession()
let newCountry:String = kOtherCountry
let updateExpectation:XCTestExpectation = expectation(
description:"update coreData location")
createUserCoreData(session:session)
{
XCTAssertNotNil(
session.country,
"failed creating data")
guard
let coreData:Database = self.coreData
else
{
return
}
session.coreDataLocation(
country:newCountry,
coreData:coreData)
{
updateExpectation.fulfill()
}
}
waitForExpectations(timeout:kWaitExpectation)
{ (error:Error?) in
XCTAssertEqual(
session.country,
newCountry,
"failed updating country")
}
}
func testFirebaseUserLocation()
{
var userLocation:FDatabaseUsersItemLocation?
let session:MSession = MSession()
let firebase:FDatabase = FDatabase()
let updateExpectation:XCTestExpectation = expectation(
description:"update firebase user location")
createFirebaseUser(
session:session,
firebase:firebase)
XCTAssertNotNil(
session.userId,
"failed creating user")
guard
let userId:String = session.userId
else
{
return
}
session.firebaseUserLocation(
country:kCountry,
firebase:firebase)
{ [weak self] in
self?.getUserLocation(
userId:userId,
firebase:firebase)
{ (location:FDatabaseUsersItemLocation?) in
userLocation = location
updateExpectation.fulfill()
}
}
waitForExpectations(timeout:kWaitExpectation)
{ [weak self] (error:Error?) in
XCTAssertNotNil(
userLocation,
"failed updating location")
XCTAssertEqual(
userLocation?.country,
self?.kCountry,
"country location mismatch")
}
}
func testFirebaseCountryUser()
{
var countryUser:FDatabaseCountriesItemUser?
let session:MSession = MSession()
let firebase:FDatabase = FDatabase()
let country:String = kCountry
let updateExpectation:XCTestExpectation = expectation(
description:"update firebase country user")
createUser(session:session)
XCTAssertNotNil(
session.userId,
"failed creating user")
guard
let userId:String = session.userId
else
{
return
}
session.firebaseCountryUser(
latitude:kLatitude,
longitude:kLongitude,
country:country,
firebase:firebase)
{ [weak self] in
self?.getCountryUser(
userId:userId,
country:country,
firebase:firebase)
{ (user:FDatabaseCountriesItemUser?) in
countryUser = user
updateExpectation.fulfill()
}
}
waitForExpectations(timeout:kWaitExpectation)
{ [weak self] (error:Error?) in
XCTAssertNotNil(
countryUser,
"failed updating country user")
XCTAssertEqual(
countryUser?.latitude,
self?.kLatitude,
"latitude mismatch")
XCTAssertEqual(
countryUser?.longitude,
self?.kLongitude,
"longitude mismatch")
}
}
}
|
mit
|
45cfa7db49ded1e81281ebf43429e733
| 25.519101 | 77 | 0.507499 | 6.042499 | false | false | false | false |
elslooo/hoverboard
|
HoverboardKit/HoverboardKit/Grid.swift
|
1
|
1996
|
/*
* Copyright (c) 2017 Tim van Elsloo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
public struct Grid {
// swiftlint:disable identifier_name
public var x: CGFloat = 0.0
public var y: CGFloat = 0.0
// swiftlint:enable identifier_name
public var xnum: CGFloat = 1.0
public var ynum: CGFloat = 1.0
public var width: CGFloat = 1.0
public var height: CGFloat = 1.0
public mutating func normalize() {
self.width = min(3.0, self.width)
self.height = min(3.0, self.height)
self.x = min(self.width - 1.0, self.x)
self.y = min(self.height - 1.0, self.y)
self.x = max(0, self.x)
self.y = max(0, self.y)
self.xnum = min(self.xnum, self.width)
self.ynum = min(self.ynum, self.height)
self.x = min(self.x, self.width - self.xnum)
self.y = min(self.y, self.height - self.ynum)
}
}
|
mit
|
2fb3edc1cae7448ac8d372d38a6d86bf
| 40.583333 | 80 | 0.672345 | 3.780303 | false | false | false | false |
mingsai/ColorWheel
|
ColorWheel/ColorWheel.swift
|
1
|
2740
|
//
// ColorWheel.swift
// ColorWheel
//
// Created by Tommie N. Carter, Jr., MBA on 4/9/15.
// Copyright (c) 2015 MING Technology. All rights reserved.
//
import UIKit
struct ColorPath {
var Path:UIBezierPath
var Color:UIColor
}
@IBDesignable
class ColorWheel: UIView {
override init (frame : CGRect) {
super.init(frame : frame)
center = self.center
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
center = self.center
}
private var image:UIImage? = nil
private var imageView:UIImageView? = nil
private var paths = [ColorPath]()
@IBInspectable var size:CGSize = CGSize.zero { didSet { setNeedsDisplay()} }
@IBInspectable var sectors:Int = 360 { didSet { setNeedsDisplay()} }
func colorAtPoint ( point: CGPoint) -> UIColor {
for colorPath in 0..<paths.count {
if paths[colorPath].Path.contains(point) {
return paths[colorPath].Color
}
}
return UIColor.clear
}
override func draw(_ rect: CGRect) {
let radius = CGFloat ( min(bounds.size.width, bounds.size.height) / 2.0 ) * 0.90
let angle:CGFloat = CGFloat(2.0) * (.pi) / CGFloat(sectors)
var colorPath:ColorPath = ColorPath(Path:UIBezierPath(), Color:UIColor.clear)
self.center = CGPoint(x: self.bounds.width - (self.bounds.width / 2.0),y: self.bounds.height - (self.bounds.height / 2.0) )
UIGraphicsBeginImageContextWithOptions(CGSize(width: bounds.size.width, height: bounds.size.height), true, 0)
UIColor.white.setFill()
UIRectFill(frame)
for sector in 0..<sectors {
let center = self.center
colorPath.Path = UIBezierPath(arcCenter: center, radius: radius, startAngle: CGFloat(sector) * angle, endAngle: (CGFloat(sector) + CGFloat(1)) * angle, clockwise: true)
colorPath.Path.addLine(to: center)
colorPath.Path.close()
let color = UIColor(hue: CGFloat(sector)/CGFloat(sectors), saturation: CGFloat(1), brightness: CGFloat(1), alpha: CGFloat(1))
color.setFill()
color.setStroke()
colorPath.Path.fill()
colorPath.Path.stroke()
colorPath.Color = color
paths.append(colorPath)
}
image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
guard image != nil else { return }
let imageView = UIImageView (image: image)
self.addSubview(imageView)
guard let oc = superview?.center else { return }
self.center = oc
}
}
|
gpl-3.0
|
14b3607a384645d2d87ac2c047f9941c
| 30.494253 | 180 | 0.60073 | 4.308176 | false | false | false | false |
embryoconcepts/TIY-Assignments
|
04 -- OutaTime/OutaTime/OutaTime/TimeCircuitsViewController.swift
|
1
|
3729
|
//
// TimeCircuitsViewController.swift
// OutaTime
//
// Created by Jennifer Hamilton on 10/8/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
// @objc protocol <- used when you make your own delegate. delegates are used to link, or grab data, from another class
// protocol is more flexible, less restrictive than a class, but holds some of the same properties
// delegate created in this class, it will be sent from the receiving class
@objc protocol DatePickerDelegate
{
func destinationDateWasChosen(dateChosen: NSDate)
}
class TimeCircuitsViewController: UIViewController, DatePickerDelegate
{
let dateFormatter = NSDateFormatter()
@IBOutlet var destinationTimeLabel: UILabel!
@IBOutlet var presentTimeLabel: UILabel!
@IBOutlet var lastTimeDepartedLabel: UILabel!
@IBOutlet var speedLabel: UILabel!
@IBOutlet var setTimeButton: UIButton!
@IBOutlet var travelBackButton: UIButton!
var timer: NSTimer?
var currentSpeed: Int = 0
var lastTimeDeparted: String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// useful source: http://www.codingexplorer.com/swiftly-getting-human-readable-date-nsdateformatter/
dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("MMM dd yyyy", options: 0, locale: NSLocale(localeIdentifier: "en-US"))
setPresentTime()
updateUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if segue.identifier == "ShowDatePickerSegue"
{
// find out what is on the other side of the segue
let datePickerVC = segue.destinationViewController
// 'as!' casts to DatePickerViewController, allowing the use of 'delegate'
as! DatePickerViewController
datePickerVC.delegate = self
}
}
// MARK: - DatePicker Delegate
func destinationDateWasChosen(dateChosen: NSDate)
{
// passing data from DatePicker class to current class when the "Back" button is selected
destinationTimeLabel.text = dateFormatter.stringFromDate(dateChosen)
}
// MARK: - Action Handlers
@IBAction func destinationButtonTapped(sender: UIButton)
{
}
@IBAction func travelBackButtonTapped(sender: UIButton)
{
startTimer()
}
// MARK: - Private
private func setPresentTime()
{
presentTimeLabel.text = dateFormatter.stringFromDate(NSDate())
}
private func startTimer()
{
if timer == nil
{
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "updateUI", userInfo: nil, repeats: true)
}
else
{
stopTimer()
}
}
private func stopTimer()
{
timer?.invalidate()
timer = nil
speedLabel.text = "\(currentSpeed - 1) MPH"
}
private func setLastTimeDeparted()
{
lastTimeDepartedLabel.text = destinationTimeLabel.text
}
func updateUI()
{
let newCount = currentSpeed
currentSpeed = Int(newCount) + 1
speedLabel.text = String(newCount) + " MPH"
if newCount == 88
{
stopTimer()
setLastTimeDeparted()
currentSpeed = 0
speedLabel.text = String(currentSpeed)
}
}
}
|
cc0-1.0
|
e2e90c80be60ae13ba781e5e77ceb4b8
| 25.628571 | 145 | 0.633315 | 5.051491 | false | false | false | false |
drmohundro/Nimble
|
Nimble/Matchers/BeAKindOf.swift
|
1
|
968
|
import Foundation
public func beAKindOf(expectedClass: AnyClass) -> MatcherFunc<NSObject?> {
return MatcherFunc { actualExpression, failureMessage in
let instance = actualExpression.evaluate()
if let validInstance = instance {
failureMessage.actualValue = "<\(NSStringFromClass(validInstance.dynamicType)) instance>"
} else {
failureMessage.actualValue = "<nil>"
}
failureMessage.postfixMessage = "be a kind of \(NSStringFromClass(expectedClass))"
return instance.hasValue && instance!.isKindOfClass(expectedClass)
}
}
extension NMBObjCMatcher {
public class func beAKindOfMatcher(expected: AnyClass) -> NMBMatcher {
return NMBObjCMatcher { actualExpression, failureMessage, location in
let expr = Expression(expression: actualExpression, location: location)
return beAKindOf(expected).matches(expr, failureMessage: failureMessage)
}
}
}
|
apache-2.0
|
90f6d92bb8e2b5fe5f785a2c61e3cc27
| 41.086957 | 101 | 0.697314 | 5.627907 | false | false | false | false |
boztalay/HabitTracker
|
HabitTracker/HabitOverviewViewController.swift
|
1
|
2150
|
//
// HabitViewController.swift
// HabitTracker
//
// Created by Ben Oztalay on 4/6/15.
// Copyright (c) 2015 Ben Oztalay. All rights reserved.
//
import UIKit
class HabitOverviewViewController: UIViewController {
// MARK: Model
var habit: Habit?
var habitAnalyzer: HabitTimeframeAnalyzer?
// MARK: Outlets
@IBOutlet weak var tableView: UITableView?
// MARK: Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.title = habit?.name
self.runHabitAnalysis()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.navigationItem.rightBarButtonItem = nil
}
func runHabitAnalysis() {
// SugarRecord.operation(inBackground: true, stackType: .SugarRecordEngineCoreData) { (context) -> () in
// if let habit = self.habit {
// self.habitAnalyzer = HabitTimeframeAnalyzer(habit: habit)
// self.habitAnalyzer?.addAndRunAllAnalyses()
//
// dispatch_async(dispatch_get_main_queue()) {
// self.tableView?.reloadData()
// }
// }
// }
}
}
extension HabitOverviewViewController: UITableViewDataSource {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let habitAnalyzer = self.habitAnalyzer {
return habitAnalyzer.analyses.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let habitAnalysisCell = tableView.dequeueReusableCellWithIdentifier(HabitAnalysisTableViewCell.ReuseIdentifier()) as! HabitAnalysisTableViewCell
let habitAnalysis = self.habitAnalyzer!.analyses[indexPath.row]
habitAnalysisCell.setHabitAnalysis(habitAnalysis)
return habitAnalysisCell
}
}
|
mit
|
de6cb02f352475686c0844bbef081c5e
| 28.452055 | 152 | 0.631628 | 4.988399 | false | false | false | false |
grpc/grpc-swift
|
Sources/GRPC/GRPCError.swift
|
1
|
11074
|
/*
* Copyright 2019, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// An error thrown by the gRPC library.
///
/// Implementation details: this is a case-less `enum` with an inner-class per error type. This
/// allows for additional error classes to be added as a SemVer minor change.
///
/// Unfortunately it is not possible to use a private inner `enum` with static property 'cases' on
/// the outer type to mirror each case of the inner `enum` as many of the errors require associated
/// values (pattern matching is not possible).
public enum GRPCError {
/// The RPC is not implemented on the server.
public struct RPCNotImplemented: GRPCErrorProtocol {
/// The path of the RPC which was called, e.g. '/echo.Echo/Get'.
public var rpc: String
public init(rpc: String) {
self.rpc = rpc
}
public var description: String {
return "RPC '\(self.rpc)' is not implemented"
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .unimplemented, message: self.description)
}
}
/// The RPC was cancelled by the client.
public struct RPCCancelledByClient: GRPCErrorProtocol {
public let description: String = "RPC was cancelled by the client"
public init() {}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .cancelled, message: self.description, cause: self)
}
}
/// The RPC did not complete before the timeout.
public struct RPCTimedOut: GRPCErrorProtocol {
/// The time limit which was exceeded by the RPC.
public var timeLimit: TimeLimit
public init(_ timeLimit: TimeLimit) {
self.timeLimit = timeLimit
}
public var description: String {
return "RPC timed out before completing"
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .deadlineExceeded, message: self.description, cause: self)
}
}
/// A message was not able to be serialized.
public struct SerializationFailure: GRPCErrorProtocol {
public let description = "Message serialization failed"
public init() {}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .internalError, message: self.description, cause: self)
}
}
/// A message was not able to be deserialized.
public struct DeserializationFailure: GRPCErrorProtocol {
public let description = "Message deserialization failed"
public init() {}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .internalError, message: self.description, cause: self)
}
}
/// The length of the received payload was longer than is permitted.
public struct PayloadLengthLimitExceeded: GRPCErrorProtocol {
public let description: String
public init(actualLength length: Int, limit: Int) {
self.description = "Payload length exceeds limit (\(length) > \(limit))"
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .resourceExhausted, message: self.description, cause: self)
}
}
/// It was not possible to compress or decompress a message with zlib.
public struct ZlibCompressionFailure: GRPCErrorProtocol {
var code: Int32
var message: String?
public init(code: Int32, message: String?) {
self.code = code
self.message = message
}
public var description: String {
if let message = self.message {
return "Zlib error: \(self.code) \(message)"
} else {
return "Zlib error: \(self.code)"
}
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .internalError, message: self.description, cause: self)
}
}
/// The decompression limit was exceeded while decompressing a message.
public struct DecompressionLimitExceeded: GRPCErrorProtocol {
/// The size of the compressed payload whose decompressed size exceeded the decompression limit.
public let compressedSize: Int
public init(compressedSize: Int) {
self.compressedSize = compressedSize
}
public var description: String {
return "Decompression limit exceeded with \(self.compressedSize) compressed bytes"
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .resourceExhausted, message: nil, cause: self)
}
}
/// It was not possible to decode a base64 message (gRPC-Web only).
public struct Base64DecodeError: GRPCErrorProtocol {
public let description = "Base64 message decoding failed"
public init() {}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .internalError, message: self.description, cause: self)
}
}
/// The compression mechanism used was not supported.
public struct CompressionUnsupported: GRPCErrorProtocol {
public let description = "The compression used is not supported"
public init() {}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .unimplemented, message: self.description, cause: self)
}
}
/// Too many, or too few, messages were sent over the given stream.
public struct StreamCardinalityViolation: GRPCErrorProtocol {
/// The stream on which there was a cardinality violation.
public let description: String
/// A request stream cardinality violation.
public static let request = StreamCardinalityViolation("Request stream cardinality violation")
/// A response stream cardinality violation.
public static let response = StreamCardinalityViolation("Response stream cardinality violation")
private init(_ description: String) {
self.description = description
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .internalError, message: self.description, cause: self)
}
}
/// The 'content-type' HTTP/2 header was missing or not valid.
public struct InvalidContentType: GRPCErrorProtocol {
/// The value of the 'content-type' header, if it was present.
public var contentType: String?
public init(_ contentType: String?) {
self.contentType = contentType
}
public var description: String {
if let contentType = self.contentType {
return "Invalid 'content-type' header: '\(contentType)'"
} else {
return "Missing 'content-type' header"
}
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .internalError, message: self.description, cause: self)
}
}
/// The ':status' HTTP/2 header was not "200".
public struct InvalidHTTPStatus: GRPCErrorProtocol {
/// The HTTP/2 ':status' header, if it was present.
public var status: String?
public init(_ status: String?) {
self.status = status
}
public var description: String {
if let status = status {
return "Invalid HTTP response status: \(status)"
} else {
return "Missing HTTP ':status' header"
}
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(
code: .init(httpStatus: self.status),
message: self.description,
cause: self
)
}
}
/// The ':status' HTTP/2 header was not "200" but the 'grpc-status' header was present and valid.
public struct InvalidHTTPStatusWithGRPCStatus: GRPCErrorProtocol {
public var status: GRPCStatus
public init(_ status: GRPCStatus) {
self.status = status
}
public var description: String {
return "Invalid HTTP response status, but gRPC status was present"
}
public func makeGRPCStatus() -> GRPCStatus {
return self.status
}
}
/// Action was taken after the RPC had already completed.
public struct AlreadyComplete: GRPCErrorProtocol {
public var description: String {
return "The RPC has already completed"
}
public init() {}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .unavailable, message: self.description, cause: self)
}
}
/// An invalid state has been reached; something has gone very wrong.
public struct InvalidState: GRPCErrorProtocol {
public var message: String
public init(_ message: String) {
self.message = "Invalid state: \(message)"
}
public var description: String {
return self.message
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .internalError, message: self.message, cause: self)
}
}
public struct ProtocolViolation: GRPCErrorProtocol {
public var message: String
public init(_ message: String) {
self.message = "Protocol violation: \(message)"
}
public var description: String {
return self.message
}
public func makeGRPCStatus() -> GRPCStatus {
return GRPCStatus(code: .internalError, message: self.message, cause: self)
}
}
}
extension GRPCError {
struct WithContext: Error, GRPCStatusTransformable {
var error: GRPCStatusTransformable
var file: StaticString
var line: Int
var function: StaticString
init(
_ error: GRPCStatusTransformable,
file: StaticString = #fileID,
line: Int = #line,
function: StaticString = #function
) {
self.error = error
self.file = file
self.line = line
self.function = function
}
func makeGRPCStatus() -> GRPCStatus {
return self.error.makeGRPCStatus()
}
}
}
/// Requirements for ``GRPCError`` types.
public protocol GRPCErrorProtocol: GRPCStatusTransformable, Equatable, CustomStringConvertible {}
extension GRPCErrorProtocol {
/// Creates a `GRPCError.WithContext` containing a `GRPCError` and the location of the call site.
internal func captureContext(
file: StaticString = #fileID,
line: Int = #line,
function: StaticString = #function
) -> GRPCError.WithContext {
return GRPCError.WithContext(self, file: file, line: line, function: function)
}
}
extension GRPCStatus.Code {
/// The gRPC status code associated with the given HTTP status code. This should only be used if
/// the RPC did not return a 'grpc-status' trailer.
internal init(httpStatus: String?) {
/// See: https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md
switch httpStatus {
case "400":
self = .internalError
case "401":
self = .unauthenticated
case "403":
self = .permissionDenied
case "404":
self = .unimplemented
case "429", "502", "503", "504":
self = .unavailable
default:
self = .unknown
}
}
}
|
apache-2.0
|
6f79102117942a213f08a46a1653aebc
| 29.59116 | 100 | 0.682229 | 4.559078 | false | false | false | false |
BridgeTheGap/KRMathInputView
|
Example/Pods/KRMathInputView/KRMathInputView/Classes/MathInkManager.swift
|
1
|
6536
|
//
// MathInkManager.swift
// TestScript
//
// Created by Joshua Park on 06/02/2017.
// Copyright © 2017 Knowre. All rights reserved.
//
import UIKit
public protocol MathInkManagerDelegate: class {
func manager(_ manager: MathInkManager, didParseTreeToLaTex string: String)
func manager(_ manager: MathInkManager, didFailToParseWith error: NSError)
func manager(_ manager: MathInkManager, didUpdateHistory state: (undo: Bool, redo: Bool))
}
public class MathInkManager: NSObject, MathInkParserDelegate {
public static func getInkManagerForTest() -> MathInkManager{
return MathInkManager()
}
public weak var delegate: MathInkManagerDelegate?
public var lineWidth: CGFloat = 3.0
private(set) var buffer: UIBezierPath?
public var ink: [InkType] {
return Array(inkCache.dropLast(inkCache.count - inkIndex))
}
public var canUndo: Bool { return inkIndex > 0 }
public var canRedo: Bool { return inkIndex < inkCache.count }
private var inkIndex = 0
private var inkCache = [InkType]()
public var parser: MathInkParser? {
didSet { parser?.delegate = self }
}
public private(set) var nodes = [TerminalNodeType]()
public private(set) var indexOfSelectedNode: Int?
// MARK: - Test
public func test(with ink: [InkType], nodes: [TerminalNodeType]) {
self.inkCache = ink
self.nodes = nodes
}
public func testSelectNode(at point: CGPoint) -> Node? {
return selectNode(at: point)
}
// MARK: - Ink
func addInkFromBuffer() {
if inkIndex < inkCache.count { inkCache.removeSubrange(inkIndex ..< inkCache.count) }
inkCache.append(StrokeInk(path: buffer!))
inkIndex += 1
}
@discardableResult func inputStream(at point: CGPoint, previousPoint: CGPoint, isLast: Bool = false) -> CGRect {
func midPoint() -> CGPoint {
return CGPoint(x: (point.x + previousPoint.x) * 0.5,
y: (point.y + previousPoint.y) * 0.5)
}
if buffer == nil {
buffer = UIBezierPath()
buffer!.lineWidth = lineWidth
buffer!.lineCapStyle = .round
buffer!.move(to: previousPoint)
}
let bufferPoint = buffer!.currentPoint
if !isLast {
buffer!.addQuadCurve(to: midPoint(), controlPoint: previousPoint)
} else {
buffer!.addQuadCurve(to: point, controlPoint: previousPoint)
addInkFromBuffer()
buffer = nil
}
delegate?.manager(self, didUpdateHistory: (canUndo, canRedo))
return { () -> CGRect in
let minX = min(point.x, bufferPoint.x) - lineWidth * 2.0
let maxX = max(point.x, bufferPoint.x) + lineWidth * 4.0
let minY = min(point.y, bufferPoint.y) - lineWidth * 2.0
let maxY = max(point.y, bufferPoint.y) + lineWidth * 4.0
return CGRect(x: minX, y: minY, width: maxX - minX, height: maxY - minY)
}()
}
func undo() -> CGRect? {
guard canUndo else { return nil }
inkIndex -= 1
delegate?.manager(self, didUpdateHistory: (canUndo, canRedo))
return { () -> CGRect in
var frame = inkCache[inkIndex].frame
frame.origin.x -= lineWidth * 2.0
frame.origin.y -= lineWidth * 2.0
frame.size.width += lineWidth * 4.0
frame.size.height += lineWidth * 4.0
return frame
}()
}
func redo() -> CGRect? {
guard canRedo else { return nil }
inkIndex += 1
delegate?.manager(self, didUpdateHistory: (canUndo, canRedo))
return { () -> CGRect in
var frame = inkCache[inkIndex - 1].frame
frame.origin.x -= lineWidth * 2.0
frame.origin.y -= lineWidth * 2.0
frame.size.width += lineWidth * 4.0
frame.size.height += lineWidth * 4.0
return frame
}()
}
func process() {
guard let parser = parser else {
// TODO: Define error
delegate?.manager(self, didFailToParseWith: NSError(domain: "tempdomain", code: 0))
return
}
parser.addInk(NSArray(array: ink.map { $0.objcType }))
parser.parse()
}
func selectNode(at point: CGPoint) -> Node? {
var candidateIndexes = [Int]()
var nodeStrokes = [[InkType]]()
var nodeFrames = [CGRect]()
for (nodeIndex, node) in nodes.enumerated() {
var strokes = [InkType]()
for i in node.indexes { strokes.append(inkCache[i]) }
let bounds = strokes.reduce(strokes.first!.frame) { $0.1.frame.union($0.0) }
nodeStrokes.append(strokes)
nodeFrames.append(bounds)
guard bounds.contains(point) else { continue }
candidateIndexes.append(nodeIndex)
}
switch candidateIndexes.count {
case 0: indexOfSelectedNode = nil
case 1: indexOfSelectedNode = candidateIndexes[0]
default:
if indexOfSelectedNode == nil {
indexOfSelectedNode = candidateIndexes[0]
} else {
if let i = candidateIndexes.index(of: indexOfSelectedNode!), i + 1 < candidateIndexes.count {
indexOfSelectedNode = candidateIndexes[i + 1]
} else {
indexOfSelectedNode = candidateIndexes[0]
}
}
}
guard let index = indexOfSelectedNode else { return nil }
return Node(ink: nodeStrokes[index], frame: nodeFrames[index])
}
// MARK: - MathInkParser delegate
public func parser(_ parser: MathInkParser, didParseTreeToLaTeX string: NSString, leafNodes: NSArray) {
guard let leafNodes = leafNodes as? [TerminalNodeType] else {
// TODO: Define error
// delegate?.manager(self, didFailToParseWith: <#T##NSError#>)
return
}
// TODO: Set leaf nodes and undefined rule nodes
// nodes = leafNodes
delegate?.manager(self, didParseTreeToLaTex: String(string))
}
public func parser(_ parser: MathInkParser, didFailWith error: NSError) {
delegate?.manager(self, didFailToParseWith: error)
}
}
|
mit
|
c2b13c4fbcace3fa4f7fc33816cdffa8
| 32.172589 | 116 | 0.571079 | 4.522491 | false | false | false | false |
austinzheng/swift
|
test/SILGen/enum.swift
|
2
|
8808
|
// RUN: %target-swift-emit-silgen -parse-stdlib -parse-as-library -module-name Swift %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
enum Boolish {
case falsy
case truthy
}
// CHECK-LABEL: sil hidden [ossa] @$ss13Boolish_casesyyF
func Boolish_cases() {
// CHECK: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type
// CHECK-NEXT: [[FALSY:%[0-9]+]] = enum $Boolish, #Boolish.falsy!enumelt
_ = Boolish.falsy
// CHECK-NEXT: [[BOOLISH:%[0-9]+]] = metatype $@thin Boolish.Type
// CHECK-NEXT: [[TRUTHY:%[0-9]+]] = enum $Boolish, #Boolish.truthy!enumelt
_ = Boolish.truthy
}
struct Int {}
enum Optionable {
case nought
case mere(Int)
}
// CHECK-LABEL: sil hidden [ossa] @$ss16Optionable_casesyySiF
func Optionable_cases(_ x: Int) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin Optionable.Type
// CHECK: [[FN:%.*]] = function_ref @$ss10OptionableO4mereyABSicABmF
// CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
// CHECK-NEXT: destroy_value [[CTOR]]
_ = Optionable.mere
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Optionable.Type
// CHECK-NEXT: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int
_ = Optionable.mere(x)
}
// CHECK-LABEL: sil shared [transparent] [thunk] [ossa] @$ss10OptionableO4mereyABSicABmF
// CHECK: [[FN:%.*]] = function_ref @$ss10OptionableO4mereyABSicABmF
// CHECK-NEXT: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
// CHECK-NEXT: return [[METHOD]]
// CHECK-NEXT: }
// CHECK-LABEL: sil shared [transparent] [ossa] @$ss10OptionableO4mereyABSicABmF
// CHECK: [[RES:%.*]] = enum $Optionable, #Optionable.mere!enumelt.1, %0 : $Int
// CHECK-NEXT: return [[RES]] : $Optionable
// CHECK-NEXT: }
protocol P {}
struct S : P {}
enum AddressOnly {
case nought
case mere(P)
case phantom(S)
}
// CHECK-LABEL: sil hidden [ossa] @$ss17AddressOnly_casesyys1SVF
func AddressOnly_cases(_ s: S) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK: [[FN:%.*]] = function_ref @$ss11AddressOnlyO4mereyABs1P_pcABmF
// CHECK-NEXT: [[CTOR:%.*]] = apply [[FN]]([[METATYPE]])
// CHECK-NEXT: destroy_value [[CTOR]]
_ = AddressOnly.mere
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: inject_enum_addr [[NOUGHT]]
// CHECK-NEXT: destroy_addr [[NOUGHT]]
// CHECK-NEXT: dealloc_stack [[NOUGHT]]
_ = AddressOnly.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[MERE:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]]
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[PAYLOAD]]
// CHECK-NEXT: store %0 to [trivial] [[PAYLOAD_ADDR]]
// CHECK-NEXT: inject_enum_addr [[MERE]]
// CHECK-NEXT: destroy_addr [[MERE]]
// CHECK-NEXT: dealloc_stack [[MERE]]
_ = AddressOnly.mere(s)
// Address-only enum vs loadable payload
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin AddressOnly.Type
// CHECK-NEXT: [[PHANTOM:%.*]] = alloc_stack $AddressOnly
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[PHANTOM]] : $*AddressOnly, #AddressOnly.phantom!enumelt.1
// CHECK-NEXT: store %0 to [trivial] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[PHANTOM]] : $*AddressOnly, #AddressOnly.phantom!enumelt.1
// CHECK-NEXT: destroy_addr [[PHANTOM]]
// CHECK-NEXT: dealloc_stack [[PHANTOM]]
_ = AddressOnly.phantom(s)
// CHECK: return
}
// CHECK-LABEL: sil shared [transparent] [thunk] [ossa] @$ss11AddressOnlyO4mereyABs1P_pcABmF
// CHECK: [[FN:%.*]] = function_ref @$ss11AddressOnlyO4mereyABs1P_pcABmF
// CHECK-NEXT: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[CANONICAL_THUNK_FN:%.*]] = function_ref @$ss1P_ps11AddressOnlyOIegir_sAA_pACIegnr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed @callee_guaranteed (@in P) -> @out AddressOnly) -> @out AddressOnly
// CHECK-NEXT: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[METHOD]])
// CHECK-NEXT: return [[CANONICAL_THUNK]] : $@callee_guaranteed (@in_guaranteed P) -> @out AddressOnly
// CHECK-NEXT: }
// CHECK-LABEL: sil shared [transparent] [ossa] @$ss11AddressOnlyO4mereyABs1P_pcABmF : $@convention
// CHECK: bb0([[ARG0:%.*]] : $*AddressOnly, [[ARG1:%.*]] : $*P, [[ARG2:%.*]] : $@thin AddressOnly.Type):
// CHECK: [[RET_DATA:%.*]] = init_enum_data_addr [[ARG0]] : $*AddressOnly, #AddressOnly.mere!enumelt.1
// CHECK-NEXT: copy_addr [take] [[ARG1]] to [initialization] [[RET_DATA]] : $*P
// CHECK-NEXT: inject_enum_addr [[ARG0]] : $*AddressOnly, #AddressOnly.mere!enumelt.1
// CHECK: return
// CHECK-NEXT: } // end sil function '$ss11AddressOnlyO4mereyABs1P_pcABmF'
enum PolyOptionable<T> {
case nought
case mere(T)
}
// CHECK-LABEL: sil hidden [ossa] @$ss20PolyOptionable_casesyyxlF
func PolyOptionable_cases<T>(_ t: T) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = alloc_stack $PolyOptionable<T>
// CHECK-NEXT: inject_enum_addr [[NOUGHT]]
// CHECK-NEXT: destroy_addr [[NOUGHT]]
// CHECK-NEXT: dealloc_stack [[NOUGHT]]
_ = PolyOptionable<T>.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<T>.Type
// CHECK-NEXT: [[MERE:%.*]] = alloc_stack $PolyOptionable<T>
// CHECK-NEXT: [[PAYLOAD:%.*]] = init_enum_data_addr [[MERE]]
// CHECK-NEXT: copy_addr %0 to [initialization] [[PAYLOAD]]
// CHECK-NEXT: inject_enum_addr [[MERE]]
// CHECK-NEXT: destroy_addr [[MERE]]
// CHECK-NEXT: dealloc_stack [[MERE]]
_ = PolyOptionable<T>.mere(t)
// CHECK-NOT: destroy_addr %0
// CHECK: return
}
// The substituted type is loadable and trivial here
// CHECK-LABEL: sil hidden [ossa] @$ss32PolyOptionable_specialized_casesyySiF
func PolyOptionable_specialized_cases(_ t: Int) {
// CHECK: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.nought!enumelt
_ = PolyOptionable<Int>.nought
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin PolyOptionable<Int>.Type
// CHECK-NEXT: [[NOUGHT:%.*]] = enum $PolyOptionable<Int>, #PolyOptionable.mere!enumelt.1, %0
_ = PolyOptionable<Int>.mere(t)
// CHECK: return
}
// Regression test for a bug where temporary allocations created as a result of
// tuple implosion were not deallocated in enum constructors.
struct String { var ptr: Builtin.NativeObject }
enum Foo { case A(P, String) }
// Curry Thunk for Foo.A(_:)
//
// CHECK-LABEL: sil shared [transparent] [thunk] [ossa] @$ss3FooO1AyABs1P_p_SStcABmF
// CHECK: [[FN:%.*]] = function_ref @$ss3FooO1AyABs1P_p_SStcABmF
// CHECK-NEXT: [[METHOD:%.*]] = partial_apply [callee_guaranteed] [[FN]](%0)
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[CANONICAL_THUNK_FN:%.*]] = function_ref @$ss1P_pSSs3FooOIegixr_sAA_pSSACIegngr_TR : $@convention(thin) (@in_guaranteed P, @guaranteed String, @guaranteed @callee_guaranteed (@in P, @owned String) -> @out Foo) -> @out Foo
// CHECK-NEXT: [[CANONICAL_THUNK:%.*]] = partial_apply [callee_guaranteed] [[CANONICAL_THUNK_FN]]([[METHOD]])
// CHECK-NEXT: return [[CANONICAL_THUNK]]
// CHECK-NEXT: }
// Foo.A(_:)
// CHECK-LABEL: sil shared [transparent] [ossa] @$ss3FooO1AyABs1P_p_SStcABmF
// CHECK: bb0([[ARG0:%.*]] : $*Foo, [[ARG1:%.*]] : $*P, [[ARG2:%.*]] : @owned $String, [[ARG3:%.*]] : $@thin Foo.Type):
// CHECK: [[PAYLOAD:%.*]] = init_enum_data_addr [[ARG0]] : $*Foo, #Foo.A!enumelt.1
// CHECK-NEXT: [[LEFT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 0
// CHECK-NEXT: [[RIGHT:%.*]] = tuple_element_addr [[PAYLOAD]] : $*(P, String), 1
// CHECK-NEXT: copy_addr [take] [[ARG1]] to [initialization] [[LEFT]] : $*P
// CHECK-NEXT: store [[ARG2]] to [init] [[RIGHT]]
// CHECK-NEXT: inject_enum_addr [[ARG0]] : $*Foo, #Foo.A!enumelt.1
// CHECK: return
// CHECK-NEXT: } // end sil function '$ss3FooO1AyABs1P_p_SStcABmF'
func Foo_cases() {
_ = Foo.A
}
enum Indirect<T> {
indirect case payload((T, other: T))
case none
}
// CHECK-LABEL: sil{{.*}} @{{.*}}makeIndirectEnum{{.*}} : $@convention(thin) <T> (@in_guaranteed T) -> @owned Indirect<T>
// CHECK: [[BOX:%.*]] = alloc_box $<τ_0_0> { var (τ_0_0, other: τ_0_0) } <T>
// CHECK: enum $Indirect<T>, #Indirect.payload!enumelt.1, [[BOX]] : $<τ_0_0> { var (τ_0_0, other: τ_0_0) } <T>
func makeIndirectEnum<T>(_ payload: T) -> Indirect<T> {
return Indirect.payload((payload, other: payload))
}
|
apache-2.0
|
e9cd6c329e4cc3be50035f06f45fc094
| 39.939535 | 240 | 0.630879 | 3.098205 | false | false | false | false |
nickdex/cosmos
|
code/mathematical_algorithms/src/check_is_square/check_is_square.swift
|
5
|
414
|
#!/usr/bin/env swift
// Part of Cosmos by OpenGenus Foundation
import Darwin
func findingSquare(num : Int) -> Bool {
let x = Int(sqrt(Double(num)))
for i in 0...x{
if(i*i == num){
return true
}
}
return false
}
let number = Int(readLine()!)
let result = findingSquare(num: number!)
if(result){
print("A perfect square")
}
else{
print("Not a perfect square")
}
|
gpl-3.0
|
601d1b0dae18b4e8119039531dfee47d
| 17.818182 | 41 | 0.594203 | 3.393443 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/PremiumSelectPeriodRowItem.swift
|
1
|
7040
|
//
// PremiumSelectPeriodRowItem.swift
// Telegram
//
// Created by Mike Renoir on 10.08.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
struct PremiumPeriod : Equatable {
enum Period {
case month
case sixMonth
case year
}
var period: Period
var price: Int64
var currency: String
var titleString: String {
return "text"
}
var priceString: String {
return "test"
}
var discountString: Int {
return 20
}
}
final class PremiumSelectPeriodRowItem : GeneralRowItem {
let periods: [PremiumPeriod]
let context: AccountContext
let selectedPeriod: PremiumPeriod
let callback: (PremiumPeriod)->Void
init(_ initialSize: NSSize, stableId: AnyHashable, context: AccountContext, periods: [PremiumPeriod], selectedPeriod: PremiumPeriod, viewType: GeneralViewType, callback:@escaping(PremiumPeriod)->Void) {
self.periods = periods
self.callback = callback
self.context = context
self.selectedPeriod = selectedPeriod
super.init(initialSize, stableId: stableId, viewType: viewType, inset: NSEdgeInsets(left: 20, right: 20))
}
override var height: CGFloat {
return (CGFloat(periods.count) * 40)
}
override func viewClass() -> AnyClass {
return PremiumSelectPeriodRowView.self
}
}
private final class PremiumSelectPeriodRowView: GeneralContainableRowView {
private class OptionView : Control {
private let imageView = ImageView()
private let title = TextView()
private let commonPrice = TextView()
private let discount = TextView()
private let borderView = View()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
layer?.cornerRadius = 10
imageView.isEventLess = true
title.userInteractionEnabled = false
title.isSelectable = false
commonPrice.userInteractionEnabled = false
commonPrice.isSelectable = false
discount.userInteractionEnabled = false
discount.isSelectable = false
commonPrice.userInteractionEnabled = false
commonPrice.isSelectable = false
addSubview(imageView)
addSubview(title)
addSubview(commonPrice)
addSubview(discount)
addSubview(borderView)
self.backgroundColor = theme.colors.background
}
override func layout() {
super.layout()
imageView.centerY(x: 15)
title.centerY(x: imageView.frame.maxX + 15)
commonPrice.centerY(x: frame.width - commonPrice.frame.width - 15)
discount.centerY(x: title.frame.maxX + 5)
borderView.frame = NSMakeRect(title.frame.minX, frame.height - .borderSize, frame.width - title.frame.minY, .borderSize)
}
func update(_ option: PremiumPeriod, selected: Bool, isLast: Bool, context: AccountContext, animated: Bool, select: @escaping(PremiumPeriod)->Void) {
let selected_image = generateChatGroupToggleSelected(foregroundColor: theme.colors.premium, backgroundColor: theme.colors.underSelectedColor)
let unselected_image = generateChatGroupToggleUnselected(foregroundColor: theme.colors.grayIcon.withAlphaComponent(0.6), backgroundColor: NSColor.black.withAlphaComponent(0.05))
self.imageView.image = selected ? selected_image : unselected_image
self.imageView.setFrameSize(20, 20)
self.borderView.backgroundColor = theme.colors.border
self.borderView.isHidden = isLast
let titleLayout = TextViewLayout(.initialize(string: option.titleString, color: theme.colors.text, font: .normal(.title)))
titleLayout.measure(width: .greatestFiniteMagnitude)
let commonPriceLayout = TextViewLayout(.initialize(string: option.priceString, color: theme.colors.grayText, font: .normal(.title)))
commonPriceLayout.measure(width: .greatestFiniteMagnitude)
let discountLayout = TextViewLayout(.initialize(string: "-\(option.discountString)%", color: theme.colors.underSelectedColor, font: .medium(.small)))
discountLayout.measure(width: .greatestFiniteMagnitude)
self.title.update(titleLayout)
self.commonPrice.update(commonPriceLayout)
self.discount.update(discountLayout)
self.discount.setFrameSize(discountLayout.layoutSize.width + 8, discountLayout.layoutSize.height + 4)
self.discount.layer?.cornerRadius = .cornerRadius
self.discount.backgroundColor = theme.colors.premium
self.discount.isHidden = option.discountString == 0
self.removeAllHandlers()
self.set(handler: { _ in
select(option)
}, for: .Click)
needsLayout = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private let optionsView = View()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(optionsView)
}
override func layout() {
super.layout()
optionsView.frame = containerView.bounds
let subviews = optionsView.subviews.compactMap { $0 as? OptionView }
var y: CGFloat = 0
for subview in subviews {
subview.setFrameOrigin(NSMakePoint(0, y))
y += subview.frame.height
}
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? PremiumSelectPeriodRowItem else {
return
}
while optionsView.subviews.count > item.periods.count {
optionsView.subviews.last?.removeFromSuperview()
}
while optionsView.subviews.count < item.periods.count {
let optionView = OptionView(frame: NSMakeSize(item.blockWidth, 40).bounds)
optionsView.addSubview(optionView)
}
for (i, option) in item.periods.enumerated() {
let subview = optionsView.subviews.compactMap { $0 as? OptionView }[i]
subview.update(option, selected: option == item.selectedPeriod, isLast: i == item.periods.count - 1, context: item.context, animated: animated, select: item.callback)
}
needsLayout = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
gpl-2.0
|
8366b680b881e93294e06ab5ab1e9c10
| 32.20283 | 206 | 0.612587 | 5.074982 | false | false | false | false |
PomTTcat/SourceCodeGuideRead_JEFF
|
RxSwiftGuideRead/RxSwift-master/Tests/RxSwiftTests/SchedulerTests.swift
|
3
|
4929
|
//
// SchedulerTests.swift
// Tests
//
// Created by Krunoslav Zaher on 7/22/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import RxSwift
import XCTest
#if os(Linux)
import Glibc
import Dispatch
#endif
import struct Foundation.Date
class ConcurrentDispatchQueueSchedulerTests: RxTest {
func createScheduler() -> SchedulerType {
return ConcurrentDispatchQueueScheduler(qos: .userInitiated)
}
}
final class SerialDispatchQueueSchedulerTests: RxTest {
func createScheduler() -> SchedulerType {
return SerialDispatchQueueScheduler(qos: .userInitiated)
}
}
class OperationQueueSchedulerTests: RxTest {
}
extension ConcurrentDispatchQueueSchedulerTests {
func test_scheduleRelative() {
let expectScheduling = expectation(description: "wait")
let start = Date()
var interval = 0.0
let scheduler = self.createScheduler()
_ = scheduler.scheduleRelative(1, dueTime: .milliseconds(500)) { _ -> Disposable in
interval = Date().timeIntervalSince(start)
expectScheduling.fulfill()
return Disposables.create()
}
waitForExpectations(timeout: 1.0) { error in
XCTAssertNil(error)
}
XCTAssertEqual(interval, 0.5, accuracy: 0.2)
}
func test_scheduleRelativeCancel() {
let expectScheduling = expectation(description: "wait")
let start = Date()
var interval = 0.0
let scheduler = self.createScheduler()
let disposable = scheduler.scheduleRelative(1, dueTime: .milliseconds(100)) { _ -> Disposable in
interval = Date().timeIntervalSince(start)
expectScheduling.fulfill()
return Disposables.create()
}
disposable.dispose()
DispatchQueue.main.asyncAfter (deadline: .now() + .milliseconds(200)) {
expectScheduling.fulfill()
}
waitForExpectations(timeout: 0.5) { error in
XCTAssertNil(error)
}
XCTAssertEqual(interval, 0.0, accuracy: 0.0)
}
func test_schedulePeriodic() {
let expectScheduling = expectation(description: "wait")
let start = Date()
let times = Synchronized([Date]())
let scheduler = self.createScheduler()
let disposable = scheduler.schedulePeriodic(0, startAfter: .milliseconds(200), period: .milliseconds(300)) { state -> Int in
times.mutate { $0.append(Date()) }
if state == 1 {
expectScheduling.fulfill()
}
return state + 1
}
waitForExpectations(timeout: 1.0) { error in
XCTAssertNil(error)
}
disposable.dispose()
XCTAssertEqual(times.value.count, 2)
XCTAssertEqual(times.value[0].timeIntervalSince(start), 0.2, accuracy: 0.1)
XCTAssertEqual(times.value[1].timeIntervalSince(start), 0.5, accuracy: 0.2)
}
func test_schedulePeriodicCancel() {
let expectScheduling = expectation(description: "wait")
var times = [Date]()
let scheduler = self.createScheduler()
let disposable = scheduler.schedulePeriodic(0, startAfter: .milliseconds(200), period: .milliseconds(300)) { state -> Int in
times.append(Date())
return state + 1
}
disposable.dispose()
DispatchQueue.main.asyncAfter (deadline: .now() + .milliseconds(300)) {
expectScheduling.fulfill()
}
waitForExpectations(timeout: 1.0) { error in
XCTAssertNil(error)
}
XCTAssertEqual(times.count, 0)
}
}
extension OperationQueueSchedulerTests {
func test_scheduleWithPriority() {
let expectScheduling = expectation(description: "wait")
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
let highPriority = OperationQueueScheduler(operationQueue: operationQueue, queuePriority: .high)
let lowPriority = OperationQueueScheduler(operationQueue: operationQueue, queuePriority: .low)
var times = [String]()
_ = highPriority.schedule(Int.self) { _ -> Disposable in
Thread.sleep(forTimeInterval: 0.4)
times.append("HIGH")
return Disposables.create()
}
_ = lowPriority.schedule(Int.self) { _ -> Disposable in
Thread.sleep(forTimeInterval: 1)
times.append("LOW")
expectScheduling.fulfill()
return Disposables.create()
}
_ = highPriority.schedule(Int.self) { _ -> Disposable in
Thread.sleep(forTimeInterval: 0.2)
times.append("HIGH")
return Disposables.create()
}
waitForExpectations(timeout: 4.0) { error in
XCTAssertNil(error)
}
XCTAssertEqual(["HIGH", "HIGH", "LOW"], times)
}
}
|
mit
|
3fe9aeb3b25c1d4ecb1900bbad39ab8f
| 27.485549 | 132 | 0.619521 | 4.972755 | false | true | false | false |
sambatech/player_sdk_ios
|
SambaPlayer/CaptionsScreen.swift
|
1
|
5788
|
//
// ErrorScreenViewController.swift
// SambaPlayer
//
// Created by Leandro Zanol on 11/22/16.
// Copyright © 2016 Samba Tech. All rights reserved.
//
import Foundation
class CaptionsScreen : UIViewController, SambaPlayerDelegate {
public private(set) var currentIndex: Int = -1
@IBOutlet var label: UILabel!
private let _player: SambaPlayer
private var _captionsRequest = [SambaMediaCaption]()
private var _captionsMap = [Int:[Caption]]()
private var _parsed = false
private var _currentCaption: Caption?
public var hasCaptions: Bool {
return _captionsRequest.count > 0
}
private struct Caption {
let index: Int, startTime: Float, endTime: Float, text: String
}
init(player: SambaPlayer) {
_player = player
super.init(nibName: "CaptionsScreen", bundle: Bundle(for: type(of: self)))
loadViewIfNeeded()
_player.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
load()
}
func changeCaption(_ value: Int) {
guard value != currentIndex,
value < _captionsRequest.count else { return }
reset(value)
// disable
if _captionsRequest[value].url == "" {
view.isHidden = true
return
}
view.isHidden = false
if _player.media.isOffline,
let captionURL = URL(string: _captionsRequest[value].url),
let response = try? String(contentsOf: captionURL) {
self.parse(response)
} else {
Helpers.requestURL(_captionsRequest[value].url, { (response: String?) in
guard let response = response else { return }
#if DEBUG
print("parsing captions...")
#endif
self.parse(response)
}) { (error, response) in
print(error ?? "error undefined", response ?? "response undefined")
}
}
}
// PLAYER DELEGATE
func onLoad() {
guard isViewLoaded else { return }
load()
}
func onProgress() {
guard _parsed else { return }
let time = _player.currentTime
guard let captions = _captionsMap[Int(time/60)] else { return }
var captionNotFound = true
// search for caption interval within time and consider only first match (in case of more than one)
for caption in captions where time >= caption.startTime && time <= caption.endTime {
captionNotFound = false
if _currentCaption == nil || _currentCaption?.index != caption.index {
label.text = caption.text
_currentCaption = caption
}
break
}
if captionNotFound {
label.text = ""
_currentCaption = nil
}
}
func onReset() {
reset()
_captionsRequest = [SambaMediaCaption]()
}
private func load() {
let media = _player.media
guard let captions = media.captions,
captions.count > 0 else { return }
let config = media.captionsConfig
let index: Int
_captionsRequest = captions
if let lang = config.language?.lowercased().replacingOccurrences(of: "_", with: "-"),
let indexConfig = _captionsRequest.index(where: { $0.language.lowercased().replacingOccurrences(of: "_", with: "-") == lang }) {
index = indexConfig
}
else if let indexApi = _captionsRequest.index(where: { $0.isDefault }) {
index = indexApi
}
else {
index = 0
}
label.textColor = UIColor(config.color)
label.font = label.font.withSize(CGFloat(config.size))
changeCaption(index)
}
private func reset(_ defaultIndex: Int = -1) {
_parsed = false
_currentCaption = nil
label.text = ""
currentIndex = defaultIndex
}
private func parse(_ captionsText: String) {
_parsed = false
_captionsMap = [Int:[Caption]]()
var captions = [Caption]()
var index = -1
var startTime: Float = 0.0
var endTime: Float = 0.0
var text = ""
var count = 0
var time = [String]()
var textLine = ""
var m = 0
var mLast = 0
func appendCaption(mapAnyway: Bool = false) {
// ignore first time or wrong index
guard index != -1 else { return }
m = Int(startTime/60)
if mapAnyway {
captions.append(Caption(index: index, startTime: startTime, endTime: endTime, text: text))
_captionsMap[mLast] = captions
return
}
if m != mLast {
_captionsMap[mLast] = captions
captions = [Caption]()
mLast = m
}
captions.append(Caption(index: index, startTime: startTime, endTime: endTime, text: text))
}
for match in Helpers.matchesForRegexInText(".+(!?[\\r\\n])", text: captionsText) {
// caption index occurence
if let r = match.range(of: "^\\d+(?=[\\r\\n]$)", options: .regularExpression) {
appendCaption()
index = Int(match[r]) ?? -1
startTime = 0.0
endTime = 0.0
text = ""
count = 1
#if DEBUG
print(index)
#endif
continue
}
switch count {
case 1:
time = Helpers.matchesForRegexInText("\\d+", text: match)
startTime = extractTime(time)
endTime = extractTime(time, offset: 4)
#if DEBUG
print(startTime, endTime)
#endif
default:
textLine = match.replacingOccurrences(of: "[\\r\\n]", with: " ", options: .regularExpression)
text += textLine.replacingOccurrences(of: "\\s+$", with: "", options: .regularExpression)
#if DEBUG
print(text)
#endif
}
count += 1
}
appendCaption(mapAnyway: true)
_parsed = true
}
private func extractTime(_ time: [String], offset: Int = 0) -> Float {
guard time.count > 0 && (time.count + offset)%4 == 0 else { return 0.0 }
let h = (Int(time[offset]) ?? 0)*3600
let m = (Int(time[offset + 1]) ?? 0)*60
let s = (Int(time[offset + 2]) ?? 0)
let ms = (Int(time[offset + 3]) ?? 0)
return Float(h + m + s) + Float(ms)/1000.0
}
}
|
mit
|
0141024a8e6541cb87786b8f814f6ed0
| 23.315126 | 131 | 0.620874 | 3.492456 | false | false | false | false |
think-dev/MadridBUS
|
Carthage/Checkouts/BRYXBanner/Example/BRYXBanner/BorderedButton.swift
|
1
|
2354
|
//
// BorderedButton.swift
//
//
// Created by Adam Binsz on 7/26/15.
//
//
import UIKit
@IBDesignable
class BorderedButton: UIButton {
@IBInspectable var borderRadius: CGFloat = 13 {
didSet {
self.layer.cornerRadius = borderRadius
}
}
@IBInspectable var borderWidth: CGFloat = 1.0 {
didSet {
self.layer.borderWidth = borderWidth
}
}
private var selectionBackgroundColor: UIColor? {
didSet {
self.setTitleColor(selectionBackgroundColor, for: .highlighted)
}
}
override var backgroundColor: UIColor? {
get {
return super.backgroundColor
}
set {
self.selectionBackgroundColor = newValue
}
}
override var tintColor: UIColor! {
didSet {
self.setTitleColor(tintColor, for: UIControlState())
self.layer.borderColor = tintColor?.cgColor
}
}
init() {
super.init(frame: CGRect.zero)
loadView()
}
override init(frame: CGRect) {
super.init(frame: frame)
loadView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
loadView()
}
convenience init(title: String, tintColor: UIColor? = UIColor.lightGray, backgroundColor: UIColor? = UIColor.white) {
self.init(frame: CGRect.zero)
self.setTitle(title, for: UIControlState())
({ self.tintColor = tintColor }())
({ self.backgroundColor = backgroundColor }())
}
private func loadView() {
super.backgroundColor = UIColor.clear
self.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15.0)
self.borderWidth = 1.0
self.layer.cornerRadius = borderRadius
if let tint = self.tintColor {
self.layer.borderColor = tint.cgColor
}
self.layer.masksToBounds = false
self.clipsToBounds = false
}
override var isHighlighted: Bool {
didSet {
if oldValue == self.isHighlighted { return }
let background = self.backgroundColor
let tint = self.tintColor
super.backgroundColor = tint
self.tintColor = background
}
}
}
|
mit
|
26106ffd096babb6d614df9726ed7a5e
| 23.520833 | 121 | 0.563721 | 5.073276 | false | false | false | false |
lorentey/swift
|
test/SILGen/dso_handle.swift
|
9
|
850
|
// RUN: %target-swift-emit-silgen -Xllvm -sil-full-demangle %s | %FileCheck %s
// CHECK: sil_global [[DSO:@__dso_handle|@__ImageBase]] : $Builtin.RawPointer
// CHECK-LABEL: sil [ossa] @main : $@convention(c)
// CHECK: bb0
// CHECK: [[DSOAddr:%[0-9]+]] = global_addr [[DSO]] : $*Builtin.RawPointer
// CHECK-NEXT: [[DSOPtr:%[0-9]+]] = address_to_pointer [[DSOAddr]] : $*Builtin.RawPointer to $Builtin.RawPointer
// CHECK-NEXT: [[DSOPtrStruct:[0-9]+]] = struct $UnsafeRawPointer ([[DSOPtr]] : $Builtin.RawPointer)
func printDSOHandle(dso: UnsafeRawPointer = #dsohandle) -> UnsafeRawPointer {
print(dso)
return dso
}
@inlinable public func printDSOHandleInlinable(dso: UnsafeRawPointer = #dsohandle) -> UnsafeRawPointer {
return dso
}
@inlinable public func callsPrintDSOHandleInlinable() {
printDSOHandleInlinable()
}
_ = printDSOHandle()
|
apache-2.0
|
444d993e1035c4792652d4f49e5e7f7b
| 34.416667 | 112 | 0.697647 | 3.427419 | false | false | false | false |
MidnightPulse/Tabman
|
Example/Tabman-Example/SettingsDismissTransitionController.swift
|
1
|
1311
|
//
// SettingsDismissTransitionController.swift
// Tabman-Example
//
// Created by Merrick Sapsford on 27/02/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
class SettingsDismissTransitionController: NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.3
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromViewController = transitionContext.viewController(forKey: .from)!
let toViewController = transitionContext.viewController(forKey: .to)!
let screenBounds = UIScreen.main.bounds
var finalFrame = fromViewController.view.frame
finalFrame.origin.y = screenBounds.size.height
UIView.animate(withDuration: transitionDuration(using: transitionContext), delay: 0.0, options: .curveEaseIn,
animations: {
fromViewController.view.frame = finalFrame
toViewController.view.alpha = 1.0
}) { (finished) in
fromViewController.view.removeFromSuperview()
transitionContext.completeTransition(finished)
}
}
}
|
mit
|
de83194bc0340cc0a60c283b140e6d3e
| 36.428571 | 117 | 0.684733 | 5.954545 | false | false | false | false |
Tantalum73/XJodel
|
XJodel/XJodel/MapViewController.swift
|
1
|
5491
|
//
// MapViewController.swift
// XJodel
//
// Created by Andreas Neusüß on 16.03.16.
// Copyright © 2016 Cocoawah. All rights reserved.
//
import Cocoa
import MapKit
class MapViewController: NSViewController {
@IBOutlet weak var blurredTitleBarVisualEffectView: NSVisualEffectView! {
didSet {
blurredTitleBarVisualEffectView.wantsLayer = true
}
}
@IBOutlet weak var mapView: MKMapView! {
didSet {
mapView.delegate = self
mapView.showsUserLocation = true
}
}
fileprivate lazy var pressGestureRecognizer : NSPressGestureRecognizer = {
let gr = NSPressGestureRecognizer (target: self, action: #selector(self.pressGestureRecognizerFired(_:)))
return gr
}()
fileprivate var currentAnnotation : MapAnnotation?
fileprivate var latestJodelLocation : JodelLocation? {
didSet {
latestJodelLocation?.saveToDefaults()
let userInfo: [AnyHashable: Any] = ["city": latestJodelLocation!.city,
"country": latestJodelLocation!.country,
"longitude": latestJodelLocation!.location.longitude,
"latitude" : latestJodelLocation!.location.latitude]
let message = Notification(name: Notification.Name(rawValue: "JodelLocationHasChanged"), object: nil, userInfo: userInfo)
NotificationCenter.default.post(message)
}
}
fileprivate let geocoder = CLGeocoder()
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
mapView.addGestureRecognizer(pressGestureRecognizer)
}
func pressGestureRecognizerFired(_ gestureRecognizer: NSPressGestureRecognizer) {
guard pressGestureRecognizer.state == NSGestureRecognizerState.began else {return}
let pointOfGesture = gestureRecognizer.location(in: mapView)
let coordinateOfGesture = mapView.convert(pointOfGesture, toCoordinateFrom: mapView)
if let annotation = currentAnnotation {
//remove annotation
mapView.removeAnnotation(annotation)
}
let newAnnotation = MapAnnotation(coordinate: coordinateOfGesture)
mapView.addAnnotation(newAnnotation)
currentAnnotation = newAnnotation
startReverseGeocodingForCoordinate(coordinateOfGesture)
}
@IBAction func centerMapButtonPressed(_ sender: NSButton) {
centerMapAroundLocation(mapView.userLocation.coordinate)
}
fileprivate func centerMapAroundLocation(_ location: CLLocationCoordinate2D) {
let span = MKCoordinateSpanMake(0.025, 0.025)
let region = MKCoordinateRegionMake(location, span)
mapView.setRegion(region, animated: true)
}
fileprivate func startReverseGeocodingForCoordinate(_ coordinate: CLLocationCoordinate2D) {
let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude)
geocoder.reverseGeocodeLocation(location) { (placemarks, error) -> Void in
if error != nil {
print("An error occured during reverse geocoging :(")
return
}
guard let firstItem = placemarks?.first,
let country = firstItem.isoCountryCode,
let city = firstItem.locality
else{return}
print("Found Location:")
print("County: \(country)")
print("City: \(city)")
self.latestJodelLocation = JodelLocation(location: coordinate, city: city, country: country)
}
}
}
extension MapViewController: MKMapViewDelegate {
func mapView(_ mapView: MKMapView, didUpdate userLocation: MKUserLocation) {
centerMapAroundLocation(userLocation.coordinate)
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let myAnnotation = annotation as? MapAnnotation else {return nil}
if(annotation.coordinate.latitude == self.mapView.userLocation.coordinate.latitude && annotation.coordinate.longitude == self.mapView.userLocation.coordinate.longitude)
{
return nil
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "customAnnotation")
if(annotationView == nil)
{
annotationView = myAnnotation.annotationView()
}
else{
annotationView!.annotation = annotation
}
return annotationView
}
/**
animate the drop in of newly added annotations.
*/
func mapView(_ mapView: MKMapView, didAdd views: [MKAnnotationView]) {
for view in views where view.reuseIdentifier == "customAnnotation"
{
let annotationView = view
let annoRect = annotationView.frame
annotationView.frame = annoRect.offsetBy(dx: 0.0, dy: -500.0)
NSAnimationContext.runAnimationGroup({ (context) -> Void in
annotationView.animator().frame = annoRect
context.duration = 0.5
}, completionHandler: { () -> Void in
})
}
}
}
|
mit
|
0c790d8a0ea8bb40137b53bc0ccdda49
| 32.668712 | 176 | 0.615525 | 5.850746 | false | false | false | false |
witekbobrowski/Stanford-CS193p-Winter-2017
|
Asteroids/Asteroids/AsteroidFieldView.swift
|
1
|
1542
|
//
// AsteroidFieldView.swift
// Asteroids
//
// Created by CS193p Instructor.
// Copyright © 2017 Stanford University. All rights reserved.
//
import UIKit
class AsteroidFieldView: UIView {
var asteroidBehavior: AsteroidBehavior? {
didSet {
for asteroid in asteroids {
oldValue?.removeAsteroid(asteroid)
asteroidBehavior?.addAsteroid(asteroid)
}
}
}
var scale: CGFloat = 0.002 // size of average asteroid (compared to bounds.size)
var minAsteroidSize: CGFloat = 0.25 // compared to average
var maxAsteroidSize: CGFloat = 2.00 // compared to average
private var asteroids: [AsteroidView] {
return subviews.flatMap { $0 as? AsteroidView }
}
func addAsteroids(count: Int, exclusionZone: CGRect = CGRect.zero) {
assert(!bounds.isEmpty, "can't add asteroids to an empty field")
let averageAsteroidSize = bounds.size * scale
for _ in 0..<count {
let asteroid = AsteroidView()
asteroid.frame.size =
(asteroid.frame.size /
(asteroid.frame.size.area / averageAsteroidSize.area)) *
CGFloat.random(in: minAsteroidSize..<maxAsteroidSize)
repeat {
asteroid.frame.origin = bounds.randomPoint
} while !exclusionZone.isEmpty && asteroid.frame.intersects(exclusionZone)
addSubview(asteroid)
asteroidBehavior?.addAsteroid(asteroid)
}
}
}
|
mit
|
f548273c75db95291f4abd28adba50e3
| 31.787234 | 86 | 0.609994 | 3.951282 | false | false | false | false |
maisa/iConv
|
App_iOS/iConv/ConfController.swift
|
1
|
7106
|
//
// ConfController.swift
// iConv
//
// Created by Leandro Paiva Andrade on 4/6/16.
// Copyright © 2016 Leandro Paiva Andrade. All rights reserved.
//
import Foundation
import UIKit
//import SwiftyJSON
class ConfController: UITableViewController{
var selectedMunicipio: Municipio!
@IBOutlet weak var cidadeText: UITextField!
@IBOutlet weak var estadoText: UITextField!
@IBOutlet weak var estadoPicker: UIPickerView!
@IBOutlet weak var cidadePicker: UIPickerView!
var buttonGoverno = false
var selectedEstado = "AC"
var test = [Municipio]()
var allMunicipios = [Municipio]()
var i = 0
var data = [[String: [Municipio]]]()
override func viewDidLoad() {
super.viewDidLoad()
// if let path = NSBundle.mainBundle().pathForResource("estados-cidades", ofType: "json") {
// if let data = NSData(contentsOfFile: path){
// let json = JSON(data: data, options: NSJSONReadingOptions.AllowFragments, error: nil)
// //print("jsonData:\(json)")
// }
// }
// runAPI()
// gradePicker.dataSource = self
// gradePicker.delegate = self
cidade()
estadoPicker.showsSelectionIndicator = true
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(true)
tableView.reloadData()
}
@IBAction func estadualButton(sender: CheckboxButton) {
let state = sender.on ? "ON" : "OFF"
if state == "ON"{
buttonGoverno = true
tableView.reloadData()
}
if state == "OFF"{
buttonGoverno = false
tableView.reloadData()
}
// print("CheckboxButton: did turn \(state)")
}
@IBAction func prefeituraButton(sender: CheckboxButton) {
let state = sender.on ? "ON" : "OFF"
if state == "ON"{
buttonGoverno = false
tableView.reloadData()
}
if state == "OFF"{
buttonGoverno = true
tableView.reloadData()
}
// print("CheckboxButton: did turn \(state)")
}
func cidade(){
// print(data)
// for item in data{
// if let test = item[estados[i]] {
// print(estados[i])
// print(test.count)
// print("")
//
// }
// i = i + 1
// }
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
if textField.placeholder == "Estado"{
toggleDatepicker(0)
}
if textField.placeholder == "Cidade"{
toggleDatepicker(1)
}
return false
}
@IBAction func closePicker(sender: UIButton) {
toggleDatepicker(0)
}
@IBAction func closeCidade(sender: UIButton) {
toggleDatepicker(1)
}
///let test = ["lala", "elel"]
func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
if pickerView.tag == 1 {
estadoText.text = estadosNome[row][1]
selectedEstado = estadosNome[row][0]
print(selectedEstado)
cidadeText.text = "Cidade"
cidadePicker.reloadAllComponents()
}
if pickerView.tag == 2 {
cidadeText.text = test[row].nome
selectedMunicipio = test[row]
}
//estadoPicker.hidden = true;
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView.tag == 1{
return estados.count
} else {
var countMuni = 0;
for item in data{
if let test = item[selectedEstado] {
//print(selectedEstado)
countMuni = test.count
// print("")
}
i = i + 1
}
return countMuni
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if pickerView.tag == 1{
return estadosNome[row][1]
} else {
if selectedEstado.isEmpty {
print(selectedEstado)
} else {
for item in data{
if let test2 = item[selectedEstado] {
test = test2
//print(selectedEstado)
// print("")
}
}
}
return test[row].nome
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 1 && indexPath.row == 0 {
toggleDatepicker(0)
}
if( indexPath.section == 2){
toggleDatepicker(1)
}
}
var estadoPickerHide = true
var cidadePickerHide = true
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if estadoPickerHide && indexPath.section == 1 && indexPath.row == 1 {
return 0
}
else if cidadePickerHide && indexPath.section == 2 && indexPath.row == 1{
return 0
}
else if buttonGoverno && indexPath.section == 2 && indexPath.row == 0{
return 0
}
else{
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
}
// override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
// if buttonGoverno && indexPath.section == 2 && indexPath.row == 0{
// return 0
// }
// return UITableViewAutomaticDimension
// }
func toggleDatepicker(toggleHide: Int){
if(toggleHide == 0){
estadoPickerHide = !estadoPickerHide
if(cidadePickerHide == false){
cidadePickerHide = true
}
}
if(toggleHide == 1){
cidadePickerHide = !cidadePickerHide
if(estadoPickerHide == false){
estadoPickerHide = true
}
}
tableView.beginUpdates()
tableView.endUpdates()
}
// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// if segue.identifier == "segueToMuni"{
// let DestView : HomeScreen = segue.destinationViewController as! HomeScreen
// //print(dict)
// DestView.data = self.selectedMunicipio
// }
//
//
// }
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
gpl-2.0
|
b4d81cf9f7bd446fa3c0c5d333f6442f
| 27.886179 | 123 | 0.529768 | 4.742991 | false | false | false | false |
sztoth/PodcastChapters
|
PodcastChapters/Utilities/Player/PodcastMonitor.swift
|
1
|
5031
|
//
// iTunesMonitor.swift
// PodcastChapters
//
// Created by Szabolcs Toth on 2016. 02. 06..
// Copyright © 2016. Szabolcs Toth. All rights reserved.
//
import AppKit
import AVFoundation
import RxOptional
import RxSwift
protocol PodcastMonitorType {
var podcast: Observable<Bool> { get }
var playing: Observable<Bool> { get }
var chapters: Observable<[Chapter]?> { get }
var playingChapterIndex: Observable<Int?> { get }
}
class PodcastMonitor: PodcastMonitorType {
var podcast: Observable<Bool> {
return itunes.nowPlaying.map({ $0?.isPodcast ?? false })
}
var playing: Observable<Bool> {
return itunes.playerState.map({ $0 == .playing ? true : false })
}
var chapters: Observable<[Chapter]?> {
return _chapters.asObservable()
}
var playingChapterIndex: Observable<Int?> {
return _playingChapterIndex.asObservable().distinctUntilChanged()
}
fileprivate let _chapters = Variable<[Chapter]?>(nil)
fileprivate let _playingChapterIndex = Variable<Int?>(nil)
fileprivate let itunes: iTunesType
fileprivate let pasteBoard: PasteBoardType
fileprivate let mediaLoader: MediaLoaderType
fileprivate let appNotificationCenter: AppNotificationCenterType
fileprivate let disposeBag = DisposeBag()
init(
itunes: iTunesType = iTunes(),
pasteBoard: PasteBoardType = PasteBoard(),
mediaLoader: MediaLoaderType,
appNotificationCenter: AppNotificationCenterType
) {
self.itunes = itunes
self.pasteBoard = pasteBoard
self.mediaLoader = mediaLoader
self.appNotificationCenter = appNotificationCenter
setupBindings()
}
}
// MARK: - Setup
fileprivate extension PodcastMonitor {
func setupBindings() {
itunes.nowPlaying
.mapToVoid()
.debug("PodcastMonitor | track changed")
.subscribe(onNext: self.reset)
.addDisposableTo(disposeBag)
itunes.playerState
.filter({ $0 == .stopped || $0 == .unknown})
.mapToVoid()
.debug("PodcastMonitor | clear notifications")
.subscribe(onNext: (self.appNotificationCenter.clearAllNotifications))
.addDisposableTo(disposeBag)
let podcastItemSignal = itunes.nowPlaying
.filterNil()
.filter({ $0.isPodcast == true })
.debug("PodcastMonitor | is podcast")
let chaptersSignal = podcastItemSignal
.map({ $0.identifier })
.flatMap(mediaLoader.URLFor)
.map({ AVAsset(url: $0) })
.flatMap(ChapterLoader.chaptersFrom)
.debug("PodcastMonitor | podcast processing")
.catchError({ _ in
self.reset()
return Observable.empty()
})
let processedChapterSignal = Observable.zip(
podcastItemSignal,
chaptersSignal,
resultSelector: processChapterWithDefaultArtwork
)
processedChapterSignal
.map({ Optional($0) })
.debug("PodcastMonitor | chapters loaded")
.bindTo(_chapters)
.addDisposableTo(disposeBag)
itunes.playerPosition
.map(findCurrentChapterIndex(forPosition:))
.bindTo(_playingChapterIndex)
.addDisposableTo(disposeBag)
playingChapterIndex
.filterNil()
.map { self._chapters.value?[$0] }
.filterNil()
.debug("PodcastMonitor | send notification")
.subscribe(onNext: sendNotification(withChapter:))
.addDisposableTo(disposeBag)
}
}
// MARK: - RxSwift methods
fileprivate extension PodcastMonitor {
func reset() {
_chapters.value = nil
_playingChapterIndex.value = nil
}
func processChapterWithDefaultArtwork(_ input: (track: iTunesTrackWrapperType, chapters: [MNAVChapter]?)) -> [Chapter] {
guard let chapters = input.chapters, !chapters.isEmpty else {
return [Chapter(cover: input.track.artwork, title: input.track.title, start: nil, duration: nil)]
}
return chapters.map { chapter in
let cover = chapter.artwork != nil ? chapter.artwork : input.track.artwork
return Chapter(cover: cover, title: chapter.title, start: chapter.time, duration: chapter.duration)
}
}
func findCurrentChapterIndex(forPosition position: Double?) -> Int? {
guard let chapters = _chapters.value, let position = position else { return nil }
for (index, chapter) in chapters.enumerated() {
if chapter.contains(position) {
return index
}
}
return nil
}
func sendNotification(withChapter chapter: Chapter) {
let appNotification = AppNotification(description: chapter.title, image: chapter.cover) {
self.pasteBoard.copy(chapter.title)
}
appNotificationCenter.deliver(appNotification)
}
}
|
mit
|
b674e2ff0656fa8501cdcb625f477891
| 31.662338 | 124 | 0.627237 | 4.859903 | false | false | false | false |
apple/swift-corelibs-foundation
|
Sources/FoundationNetworking/URLCredentialStorage.swift
|
1
|
11167
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
/*!
@class URLCredential.Storage
@discussion URLCredential.Storage implements a singleton object (shared instance) which manages the shared credentials cache. Note: Whereas in Mac OS X any application can access any credential with a persistence of URLCredential.Persistence.permanent provided the user gives permission, in iPhone OS an application can access only its own credentials.
*/
open class URLCredentialStorage: NSObject {
private static var _shared = URLCredentialStorage()
/*!
@method sharedCredentialStorage
@abstract Get the shared singleton authentication storage
@result the shared authentication storage
*/
open class var shared: URLCredentialStorage { return _shared }
private let _lock: NSLock
private var _credentials: [URLProtectionSpace: [String: URLCredential]]
private var _defaultCredentials: [URLProtectionSpace: URLCredential]
public override init() {
_lock = NSLock()
_credentials = [:]
_defaultCredentials = [:]
}
convenience init(ephemeral: Bool) {
// Some URLCredentialStorages must be ephemeral, to support ephemeral URLSessions. They should not write anything to persistent storage.
// All URLCredentialStorage instances are _currently_ ephemeral, so there's no need to record the value of 'ephemeral' here, but if we implement persistent storage in the future using platform secure storage, implementers of that functionality will have to heed this flag here.
self.init()
}
/*!
@method credentialsForProtectionSpace:
@abstract Get a dictionary mapping usernames to credentials for the specified protection space.
@param protectionSpace An URLProtectionSpace indicating the protection space for which to get credentials
@result A dictionary where the keys are usernames and the values are the corresponding URLCredentials.
*/
open func credentials(for space: URLProtectionSpace) -> [String : URLCredential]? {
_lock.lock()
defer { _lock.unlock() }
return _credentials[space]
}
/*!
@method allCredentials
@abstract Get a dictionary mapping URLProtectionSpaces to dictionaries which map usernames to URLCredentials
@result an NSDictionary where the keys are URLProtectionSpaces
and the values are dictionaries, in which the keys are usernames
and the values are URLCredentials
*/
open var allCredentials: [URLProtectionSpace : [String : URLCredential]] {
_lock.lock()
defer { _lock.unlock() }
return _credentials
}
/*!
@method setCredential:forProtectionSpace:
@abstract Add a new credential to the set for the specified protection space or replace an existing one.
@param credential The credential to set.
@param space The protection space for which to add it.
@discussion Multiple credentials may be set for a given protection space, but each must have
a distinct user. If a credential with the same user is already set for the protection space,
the new one will replace it.
*/
open func set(_ credential: URLCredential, for space: URLProtectionSpace) {
guard credential.persistence != .synchronizable else {
// Do what logged-out-from-iCloud Darwin does, and refuse to save synchronizable credentials when a sync service is not available (which, in s-c-f, is always)
return
}
guard credential.persistence != .none else {
return
}
_lock.lock()
let needsNotification = _setWhileLocked(credential, for: space)
_lock.unlock()
if needsNotification {
_sendNotificationWhileUnlocked()
}
}
/*!
@method removeCredential:forProtectionSpace:
@abstract Remove the credential from the set for the specified protection space.
@param credential The credential to remove.
@param space The protection space for which a credential should be removed
@discussion The credential is removed from both persistent and temporary storage. A credential that
has a persistence policy of URLCredential.Persistence.synchronizable will fail.
See removeCredential:forProtectionSpace:options.
*/
open func remove(_ credential: URLCredential, for space: URLProtectionSpace) {
remove(credential, for: space, options: nil)
}
/*!
@method removeCredential:forProtectionSpace:options
@abstract Remove the credential from the set for the specified protection space based on options.
@param credential The credential to remove.
@param space The protection space for which a credential should be removed
@param options A dictionary containing options to consider when removing the credential. This should
be used when trying to delete a credential that has the URLCredential.Persistence.synchronizable policy.
Please note that when URLCredential objects that have a URLCredential.Persistence.synchronizable policy
are removed, the credential will be removed on all devices that contain this credential.
@discussion The credential is removed from both persistent and temporary storage.
*/
open func remove(_ credential: URLCredential, for space: URLProtectionSpace, options: [String : AnyObject]? = [:]) {
if credential.persistence == .synchronizable {
guard let options = options,
let removeSynchronizable = options[NSURLCredentialStorageRemoveSynchronizableCredentials] as? NSNumber,
removeSynchronizable.boolValue == true else {
return
}
}
var needsNotification = false
_lock.lock()
if let user = credential.user {
if _credentials[space]?[user] == credential {
_credentials[space]?[user] = nil
needsNotification = true
// If we remove the last entry, remove the protection space.
if _credentials[space]?.count == 0 {
_credentials[space] = nil
}
}
}
// Also, look for a default object, if it exists, but check equality.
if let defaultCredential = _defaultCredentials[space],
defaultCredential == credential {
_defaultCredentials[space] = nil
needsNotification = true
}
_lock.unlock()
if needsNotification {
_sendNotificationWhileUnlocked()
}
}
/*!
@method defaultCredentialForProtectionSpace:
@abstract Get the default credential for the specified protection space.
@param space The protection space for which to get the default credential.
*/
open func defaultCredential(for space: URLProtectionSpace) -> URLCredential? {
_lock.lock()
defer { _lock.unlock() }
return _defaultCredentials[space]
}
/*!
@method setDefaultCredential:forProtectionSpace:
@abstract Set the default credential for the specified protection space.
@param credential The credential to set as default.
@param space The protection space for which the credential should be set as default.
@discussion If the credential is not yet in the set for the protection space, it will be added to it.
*/
open func setDefaultCredential(_ credential: URLCredential, for space: URLProtectionSpace) {
guard credential.persistence != .synchronizable else {
return
}
guard credential.persistence != .none else {
return
}
_lock.lock()
let needsNotification = _setWhileLocked(credential, for: space, isDefault: true)
_lock.unlock()
if needsNotification {
_sendNotificationWhileUnlocked()
}
}
private func _setWhileLocked(_ credential: URLCredential, for space: URLProtectionSpace, isDefault: Bool = false) -> Bool {
var modified = false
if let user = credential.user {
if _credentials[space] == nil {
_credentials[space] = [:]
}
modified = _credentials[space]![user] != credential
_credentials[space]![user] = credential
}
if isDefault || _defaultCredentials[space] == nil {
modified = modified || _defaultCredentials[space] != credential
_defaultCredentials[space] = credential
}
return modified
}
private func _sendNotificationWhileUnlocked() {
let notification = Notification(name: .NSURLCredentialStorageChanged, object: self, userInfo: nil)
NotificationCenter.default.post(notification)
}
}
extension URLCredentialStorage {
public func getCredentials(for protectionSpace: URLProtectionSpace, task: URLSessionTask, completionHandler: ([String : URLCredential]?) -> Void) {
completionHandler(credentials(for: protectionSpace))
}
public func set(_ credential: URLCredential, for protectionSpace: URLProtectionSpace, task: URLSessionTask) {
set(credential, for: protectionSpace)
}
public func remove(_ credential: URLCredential, for protectionSpace: URLProtectionSpace, options: [String : AnyObject]? = [:], task: URLSessionTask) {
remove(credential, for: protectionSpace, options: options)
}
public func getDefaultCredential(for space: URLProtectionSpace, task: URLSessionTask, completionHandler: (URLCredential?) -> Void) {
completionHandler(defaultCredential(for: space))
}
public func setDefaultCredential(_ credential: URLCredential, for protectionSpace: URLProtectionSpace, task: URLSessionTask) {
setDefaultCredential(credential, for: protectionSpace)
}
}
extension Notification.Name {
/*!
@const NSURLCredentialStorageChangedNotification
@abstract This notification is sent on the main thread whenever
the set of stored credentials changes.
*/
public static let NSURLCredentialStorageChanged = NSNotification.Name(rawValue: "NSURLCredentialStorageChangedNotification")
}
/*
* NSURLCredentialStorageRemoveSynchronizableCredentials - (NSNumber value)
* A key that indicates either @YES or @NO that credentials which contain the NSURLCredentialPersistenceSynchronizable
* attribute should be removed. If the key is missing or the value is @NO, then no attempt will be made
* to remove such a credential.
*/
public let NSURLCredentialStorageRemoveSynchronizableCredentials: String = "NSURLCredentialStorageRemoveSynchronizableCredentials"
|
apache-2.0
|
a7d00caa24167f2435324d64ba3adfb4
| 41.785441 | 356 | 0.688726 | 5.343062 | false | false | false | false |
andrzejsemeniuk/ASToolkit
|
ASToolkit/Loop.swift
|
1
|
985
|
//
// Loop.swift
// ASToolkit
//
// Created by andrzej semeniuk on 2/7/17.
// Copyright © 2017 Andrzej Semeniuk. All rights reserved.
//
import Foundation
public func loop(_ count:Int, block:()->()) {
var i:Int = 0
let count = 0 < count ? count : 0
while i < count {
block()
i = i+1
}
}
public func loopWithIndex(_ count:Int, block:(Int)->()) {
var i:Int = 0
let count = 0 < count ? count : 0
while i < count {
block(i)
i = i+1
}
}
public func loop(upTo count:Int, block:()->(Bool)) {
var i:Int = 0
let count = 0 < count ? count : 0
while i < count {
if block() {
i = i+1
}
else {
break
}
}
}
public func loopWithIndex(upTo count:Int, block:(Int)->(Bool)) {
var i:Int = 0
let count = 0 < count ? count : 0
while i < count {
if block(i) {
i = i+1
}
else {
break
}
}
}
|
mit
|
875e2d101a36255b45095da6c3c0af85
| 17.566038 | 64 | 0.476626 | 3.358362 | false | false | false | false |
justindarc/focus
|
Blockzilla/BrowserToolset.swift
|
4
|
6030
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
protocol BrowserToolsetDelegate: class {
func browserToolsetDidPressBack(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressForward(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressReload(_ browserToolbar: BrowserToolset)
func browserToolsetDidLongPressReload(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressStop(_ browserToolbar: BrowserToolset)
func browserToolsetDidPressSettings(_ browserToolbar: BrowserToolset)
}
class BrowserToolset {
weak var delegate: BrowserToolsetDelegate?
let backButton = InsetButton()
let forwardButton = InsetButton()
let stopReloadButton = InsetButton()
let settingsButton = InsetButton()
init() {
backButton.tintColor = UIConstants.colors.toolbarButtonNormal
backButton.setImage(#imageLiteral(resourceName: "icon_back_active"), for: .normal)
backButton.setImage(#imageLiteral(resourceName: "icon_back_active").alpha(0.4), for: .disabled)
backButton.addTarget(self, action: #selector(didPressBack), for: .touchUpInside)
backButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
backButton.accessibilityLabel = UIConstants.strings.browserBack
backButton.isEnabled = false
forwardButton.tintColor = UIConstants.colors.toolbarButtonNormal
forwardButton.setImage(#imageLiteral(resourceName: "icon_forward_active"), for: .normal)
forwardButton.setImage(#imageLiteral(resourceName: "icon_forward_active").alpha(0.4), for: .disabled)
forwardButton.addTarget(self, action: #selector(didPressForward), for: .touchUpInside)
forwardButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
forwardButton.accessibilityLabel = UIConstants.strings.browserForward
forwardButton.isEnabled = false
stopReloadButton.tintColor = UIConstants.colors.toolbarButtonNormal
stopReloadButton.setImage(#imageLiteral(resourceName: "icon_refresh_menu"), for: .normal)
stopReloadButton.setImage(#imageLiteral(resourceName: "icon_refresh_menu").alpha(0.4), for: .disabled)
stopReloadButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
let longPressGestureStopReloadButton = UILongPressGestureRecognizer(target: self, action: #selector(didLongPressReload))
stopReloadButton.addGestureRecognizer(longPressGestureStopReloadButton)
stopReloadButton.addTarget(self, action: #selector(didPressStopReload), for: .touchUpInside)
stopReloadButton.accessibilityIdentifier = "BrowserToolset.stopReloadButton"
settingsButton.tintColor = UIConstants.colors.toolbarButtonNormal
settingsButton.addTarget(self, action: #selector(didPressSettings), for: .touchUpInside)
settingsButton.accessibilityLabel = UIConstants.strings.browserSettings
settingsButton.accessibilityIdentifier = "HomeView.settingsButton"
settingsButton.contentEdgeInsets = UIConstants.layout.toolbarButtonInsets
setHighlightWhatsNew(shouldHighlight: shouldShowWhatsNew())
}
var canGoBack: Bool = false {
didSet {
backButton.isEnabled = canGoBack
backButton.alpha = canGoBack ? 1 : UIConstants.layout.browserToolbarDisabledOpacity
}
}
var canGoForward: Bool = false {
didSet {
forwardButton.isEnabled = canGoForward
forwardButton.alpha = canGoForward ? 1 : UIConstants.layout.browserToolbarDisabledOpacity
}
}
var isLoading: Bool = false {
didSet {
if isLoading {
stopReloadButton.setImage(#imageLiteral(resourceName: "icon_stop_menu"), for: .normal)
stopReloadButton.accessibilityLabel = UIConstants.strings.browserStop
} else {
stopReloadButton.setImage(#imageLiteral(resourceName: "icon_refresh_menu"), for: .normal)
stopReloadButton.accessibilityLabel = UIConstants.strings.browserReload
}
}
}
@objc private func didPressBack() {
delegate?.browserToolsetDidPressBack(self)
}
@objc private func didPressForward() {
delegate?.browserToolsetDidPressForward(self)
}
@objc private func didPressStopReload() {
if isLoading {
delegate?.browserToolsetDidPressStop(self)
} else {
delegate?.browserToolsetDidPressReload(self)
}
}
@objc func didLongPressReload(recognizer: UILongPressGestureRecognizer) {
if recognizer.state == .began && !isLoading {
stopReloadButton.alpha = 1
delegate?.browserToolsetDidLongPressReload(self)
}
}
@objc private func didPressSettings() {
delegate?.browserToolsetDidPressSettings(self)
}
func setHighlightWhatsNew(shouldHighlight: Bool) {
if shouldHighlight {
settingsButton.setImage(UIImage(named: "preferences_updated"), for: .normal)
} else {
settingsButton.setImage(#imageLiteral(resourceName: "icon_settings"), for: .normal)
}
}
}
extension BrowserToolset: WhatsNewDelegate {
func shouldShowWhatsNew() -> Bool {
let counter = UserDefaults.standard.integer(forKey: AppDelegate.prefWhatsNewCounter)
return counter != 0
}
func didShowWhatsNew() {
UserDefaults.standard.set(AppInfo.shortVersion, forKey: AppDelegate.prefWhatsNewDone)
UserDefaults.standard.removeObject(forKey: AppDelegate.prefWhatsNewCounter)
}
}
extension UIImage {
func alpha(_ value: CGFloat) -> UIImage {
let imageRenderer = UIGraphicsImageRenderer(size: size)
return imageRenderer.image(actions: { (context) in
draw(at: .zero, blendMode: .normal, alpha: value)
})
}
}
|
mpl-2.0
|
ffb87eaacc87893ab6cbd1b350dd485a
| 42.071429 | 128 | 0.711609 | 5.189329 | false | false | false | false |
X140Yu/Lemon
|
Lemon/Features/Events/EventsViewController.swift
|
1
|
6053
|
import UIKit
import Result
import RxSwift
import Moya
import Moya_ObjectMapper
import AsyncDisplayKit
class EventsViewController: UIViewController {
let tableNode = ASTableNode()
let refreshControl = UIRefreshControl()
var events = [GitHubEvent]()
let disposeBag = DisposeBag()
struct State {
var itemCount: Int
var page: Int
var fetchingMore: Bool
static let empty = State(itemCount: 0, page: 1, fetchingMore: false)
}
enum Action {
case beginBatchFetch
case endBatchFetch(resultCount: Int)
}
fileprivate(set) var state: State = .empty
override func viewDidLoad() {
super.viewDidLoad()
let firstPage = GitHubProvider
.request(.User)
.mapObject(User.self)
.flatMap({ (user) -> Single<[GitHubEvent]> in
guard let login = user.login else {
return Single<[GitHubEvent]>.just([])
}
CacheManager.cachedUsername = user.login
return GitHubProvider
.request(GitHub.Events(login: login, page: 1))
.timeout(10, scheduler: MainScheduler.instance)
.mapArray(GitHubEvent.self)
.observeOn(MainScheduler.instance)
})
refreshControl.backgroundColor = UIColor.clear
refreshControl.tintColor = UIColor.lmLightGrey
refreshControl.rx.controlEvent(.valueChanged)
.flatMap { _ in
return firstPage
}
.subscribe(onNext: { [weak self] events in
guard let `self` = self else { return }
self.events = events
self.refreshControl.endRefreshing()
self.state.page = 1
self.state.itemCount = events.count
self.state = EventsViewController.handleAction(.endBatchFetch(resultCount: 20), fromState: self.state)
self.tableNode.reloadData()
}, onError: { [weak self] error in
guard let `self` = self else { return }
self.refreshControl.endRefreshing()
})
.disposed(by: disposeBag)
tableNode.view.addSubview(refreshControl)
view.addSubnode(tableNode)
tableNode.dataSource = self
tableNode.delegate = self
refreshControl.refreshManually()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
let tabBarheight = self.tabBarController?.tabBar.bounds.size.height ?? 0
tableNode.frame = CGRect(x: 0, y: 0, width: view.bounds.width, height: view.bounds.height - tabBarheight)
}
func deal(url: URL?) {
Router.handleURL(url, navigationController)
}
}
extension EventsViewController: ASTableDataSource, ASTableDelegate {
func tableNode(_ tableNode: ASTableNode, constrainedSizeForRowAt indexPath: IndexPath) -> ASSizeRange {
let width = UIScreen.main.bounds.size.width;
let min = CGSize(width: width, height: 100)
let max = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
return ASSizeRange(min: min, max: max)
}
func tableNode(_ tableNode: ASTableNode, didSelectRowAt indexPath: IndexPath) {
tableNode.deselectRow(at: indexPath, animated: true)
let event = events[indexPath.row]
if let URLString = event.repo?.url {
self.deal(url: URL(string: URLString))
}
}
func numberOfSections(in tableNode: ASTableNode) -> Int {
return 1
}
func tableNode(_ tableNode: ASTableNode, numberOfRowsInSection section: Int) -> Int {
var count = events.count
if state.fetchingMore {
count += 1
}
return count
}
func tableNode(_ tableNode: ASTableNode, nodeForRowAt indexPath: IndexPath) -> ASCellNode {
let rowCount = self.tableNode(tableNode, numberOfRowsInSection: 0)
if state.fetchingMore && indexPath.row == rowCount - 1 {
let node = TailLoadingCellNode()
node.style.height = ASDimensionMake(44.0)
return node
}
let event = events[indexPath.row]
let viewModel = EventCellViewModel(event: event)
let node = EventCellNode(viewModel: viewModel)
viewModel.outputs.linkURL.asObservable()
.subscribe(onNext: { [weak self] URL in
self?.deal(url: URL)
}).addDisposableTo(node.bag)
return node
}
func tableNode(_ tableNode: ASTableNode, willBeginBatchFetchWith context: ASBatchContext) {
if events.count == 0 {
context.completeBatchFetching(true)
return
}
state.fetchingMore = true
GitHubProvider
.request(.User)
.mapObject(User.self)
.flatMap { user -> Single<[GitHubEvent]> in
if let login = user.login {
return GitHubProvider
.request(.Events(login: login, page: self.state.page + 1))
.mapArray(GitHubEvent.self)
.timeout(10, scheduler: MainScheduler.instance)
.observeOn(MainScheduler.instance)
}
return Single<[GitHubEvent]>.just([])
}
.subscribe(onSuccess: { (e) in
let action = Action.endBatchFetch(resultCount: e.count)
let oldState = self.state
self.state = EventsViewController.handleAction(action, fromState: oldState)
self.state.page += 1
self.state.fetchingMore = false
var initial = self.events.count - 1
let indexPaths = e.map { _ -> IndexPath in
initial += 1
return IndexPath(row: initial, section: 0)
}
self.events.append(contentsOf: e)
self.state.itemCount = self.events.count
self.tableNode.insertRows(at: indexPaths, with: UITableViewRowAnimation.fade)
context.completeBatchFetching(true)
}, onError: { e in
let e = e as! MoyaError
if e.response?.statusCode == 422 {
ProgressHUD.showText("GitHub API only support 300 events :(")
}
context.completeBatchFetching(true)
})
.addDisposableTo(disposeBag)
}
fileprivate static func handleAction(_ action: Action, fromState state: State) -> State {
var state = state
switch action {
case .beginBatchFetch:
state.fetchingMore = true
case let .endBatchFetch(resultCount):
state.itemCount += resultCount
state.fetchingMore = false
}
return state
}
}
|
gpl-3.0
|
49b1c5ed958ffd2fb1a9560595230af2
| 30.201031 | 110 | 0.664133 | 4.490356 | false | false | false | false |
swift-lang/swift-k
|
tests/apps/multiple_apps/multiple_apps.swift
|
2
|
660
|
type file;
app (file out, file err) date ()
{
date stdout=@out stderr=@err;
}
app (file out, file err) cat (file dates[])
{
cat @dates stdout=@out stderr=@err;
}
int loops = toInt(arg("loops", "10"));
file out[] <simple_mapper; location="output", prefix="foo", suffix=".out">;
file err[] <simple_mapper; location="output", prefix="foo", suffix=".err">;
foreach item in [1:loops] {
tracef("Item : %d\n", item);
(out[item], err[item]) = date();
}
file fin_out <simple_mapper; location="output", prefix="final", suffix=".out">;
file fin_err <simple_mapper; location="output", prefix="final", suffix=".out">;
(fin_out, fin_err) = cat(out);
|
apache-2.0
|
a8d96b3fee6ed5af09f3235578d5f2a7
| 23.444444 | 79 | 0.627273 | 3.069767 | false | false | true | false |
RameshRM/just-now
|
JustNow/JustNow/AppDelegate.swift
|
1
|
6024
|
//
// AppDelegate.swift
// JustNow
//
// Created by Mahadevan, Ramesh on 7/25/15.
// Copyright (c) 2015 GoliaMania. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var installBase:InstallBase = InstallBase();
var registrationModel: RegistrationModel!;
var appInfo:AppInfo = AppInfo(appId: NSBundle.mainBundle().bundleIdentifier!, bundleProperties: NSBundle.mainBundle().infoDictionary!);
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
println("Launched ....");
// if(SessionManager.isSignedIn()){
// let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil);
// var viewController = mainStoryboard.instantiateViewControllerWithIdentifier("homeScreen") as! UIViewController;
// self.window!.rootViewController = viewController;
// }
if(installBase.installedDevice.isVersion(InstalledDevice.IOS8)){
application.registerForRemoteNotifications();
}else{
application.registerForRemoteNotificationTypes(.Alert | .Badge | .Sound);
}
return true;
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
var version = NSBundle.mainBundle().infoDictionary?["CFBundleVersion"] as? String;
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.golia.mania.JustNow" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("JustNow", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("JustNow.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData){
NSLog("Device Token: \(deviceToken)");
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError){
}
}
|
apache-2.0
|
bbf692a5954c11cd4ce1bde5ba576865
| 46.0625 | 290 | 0.687251 | 5.894325 | false | false | false | false |
MadArkitekt/Swift_Tutorials_And_Demos
|
CustomViewTransitions/CustomViewTransitions/ViewController.swift
|
1
|
1113
|
//
// ViewController.swift
// CustomViewTransitions
//
// Created by Edward Salter on 9/6/14.
// Copyright (c) 2014 Edward Salter. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let transitionManager = TransAnimateManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
let toViewController = segue.destinationViewController as UIViewController
toViewController.transitioningDelegate = self.transitionManager
}
@IBAction func unwindToViewController(segue: UIStoryboardSegue)
{
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return self.presentingViewController == nil ? UIStatusBarStyle.Default : UIStatusBarStyle.LightContent
}
}
|
gpl-2.0
|
921adac0bacbe060c7a4d7e862107b44
| 26.825 | 110 | 0.697215 | 5.649746 | false | false | false | false |
oddnetworks/odd-sample-apps
|
apple/ios/OddSampleApp/OddSampleApp/SearchTableViewController.swift
|
1
|
11050
|
//
// SearchTableViewController.swift
// OddSampleApp
//
// Created by Matthew Barth on 2/16/16.
// Copyright © 2016 Odd Networks. All rights reserved.
//
import UIKit
import OddSDK
class SearchTableViewController: UITableViewController, UITextFieldDelegate {
var searchField: UITextField?
var searching: Bool = false
var foundVideos: Array<OddVideo>?
var foundCollections: Array<OddMediaObjectCollection>?
var selectedCollection: OddMediaObjectCollection?
var selectedVideo: OddVideo?
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
configureNavBar()
self.tableView.backgroundColor = ThemeManager.defaultManager.currentTheme().tableViewBackgroundColor
self.tableView.contentInset = UIEdgeInsetsMake( -36, 0, 0, 0)
self.tableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func viewDidAppear(_ animated: Bool) {
self.activateSearchField()
}
func haveSearchResults() -> Bool {
return self.foundVideos != nil || self.foundCollections != nil
}
func configureNavBar() {
let width = self.view.frame.width * 0.7
searchField = UITextField(frame: CGRect(x: 0, y: 0, width: width, height: 30))
if let searchField = searchField {
searchField.backgroundColor = UIColor.white
searchField.placeholder = "Search"
searchField.returnKeyType = .search
searchField.delegate = self
searchField.tintColor = .darkGray
configureTextFieldElements(searchField)
let searchItem = UIBarButtonItem(customView: searchField)
self.navigationItem.leftBarButtonItem = searchItem
}
let cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(SearchTableViewController.exitSearch))
self.navigationItem.rightBarButtonItem = cancelButton
}
func configureTextFieldElements(_ textField: UITextField) {
let iconSize: CGFloat = 18
let container = UIView(frame: CGRect(x: 4, y: 0, width: 28, height: 18))
let magnifyView = UIImageView(frame: CGRect(x: 0, y: 0, width: iconSize, height: iconSize))
magnifyView.image = UIImage(named: "magnify")
magnifyView.image = magnifyView.image!.withRenderingMode(.alwaysTemplate)
magnifyView.tintColor = .lightGray
container.addSubview(magnifyView)
magnifyView.center.x += 4
// magnifyView.center.y -= 4
textField.leftView = container
textField.leftViewMode = .always
}
func fetchSearchResults( _ term: String ) {
OddContentStore.sharedStore.searchForTerm(term) { (videos, collections) -> Void in
print("Found \(videos!.count) videos and \(collections!.count) collections")
let courseCollections = self.cleanCollections(collections)
self.foundCollections = courseCollections
self.foundVideos = videos
DispatchQueue.main.async(execute: { () -> Void in
self.tableView.reloadData()
})
}
}
func cleanCollections(_ collections: Array<OddMediaObjectCollection>?) -> Array<OddMediaObjectCollection>? {
if collections == nil { return nil }
return collections
}
func exitSearch() {
print("Exit Search")
performSegue(withIdentifier: "exitSearchUnwind", sender: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return haveSearchResults() ? 2 : 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if !haveSearchResults() {
return 1
}
if section == 0 { // collections
if let collections = foundCollections {
return collections.count > 0 ? collections.count : 1
}
return 1
} else {
if let videos = foundVideos {
return videos.count > 0 ? videos.count : 1
}
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "SearchInfoCell", for: indexPath) as! VideoInfoTableViewCell
self.tableView.separatorColor = UIColor.clear
cell.addSeparatorLineToBottom()
cell.textLabel?.text = ""
cell.notesLabel.text = ""
cell.accessoryType = .none
let titleColor = ThemeManager.defaultManager.currentTheme().tableViewCellTitleLabelColor
let subtitleColor = ThemeManager.defaultManager.currentTheme().tableViewCellTextLabelColor
cell.textLabel?.textColor = titleColor
cell.detailTextLabel?.textColor = subtitleColor
cell.titleLabel?.textColor = titleColor
cell.notesLabel?.textColor = subtitleColor
cell.backgroundColor = .clear
cell.contentView.backgroundColor = .clear
cell.thumbnailImageView.isHidden = false
cell.durationBackground?.isHidden = true
if haveSearchResults() {
if (indexPath as NSIndexPath).section == 0 { // collections
if let collections = foundCollections {
if collections.count == 0 {
cell.titleLabel.text = "No Collections Found"
} else {
let currentCollection = collections[indexPath.row]
currentCollection.thumbnail({ (thumbnail) -> () in
cell.thumbnailImageView.image = thumbnail
})
cell.titleLabel.text = currentCollection.title
cell.notesLabel.text = currentCollection.notes
cell.accessoryType = .disclosureIndicator
}
}
} else {
if let videos = foundVideos {
if videos.count == 0 {
cell.titleLabel.text = "No Videos Found"
} else {
let currentVideo = videos[indexPath.row]
// currentVideo.configureCell(cell)
cell.backgroundColor = .clear
currentVideo.thumbnail({ (thumbnail) -> () in
cell.thumbnailImageView.image = thumbnail
})
cell.titleLabel.text = currentVideo.title
cell.notesLabel.text = currentVideo.notes
cell.durationBackground?.isHidden = false
cell.durationLabel?.text = currentVideo.durationAsTimeString()
cell.accessoryType = .disclosureIndicator
}
}
} // videos
} else {
cell.titleLabel.text = ""
cell.thumbnailImageView.image = nil
cell.thumbnailImageView.isHidden = true
cell.textLabel?.text = "No Search Results..."
cell.textLabel?.textColor = ThemeManager.defaultManager.currentTheme().tableViewCellTitleLabelColor
self.tableView.separatorStyle = .none
}
// if haveSearchResults() {
// cell.backgroundColor = UIColor(red:0.08, green:0.09, blue:0.15, alpha:1)
// cell.contentView.backgroundColor = UIColor(red:0.08, green:0.09, blue:0.15, alpha:1)
// } else {
cell.backgroundColor = .clear
cell.contentView.backgroundColor = .clear
// }
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let text = section == 0 ? "Collections" : "Videos"
let frame = CGRect(x: 0, y: 0, width: tableView.frame.width, height: 29)
let headerView = UIView(frame: frame)
headerView.backgroundColor = ThemeManager.defaultManager.currentTheme().tableViewSectionHeaderBackgroundColor
let labelFrame = CGRect(x: 8, y: 0, width: tableView.frame.width - 8, height: 29)
let label = UILabel(frame: labelFrame)
label.text = text
label.textColor = ThemeManager.defaultManager.currentTheme().tableViewSectionHeaderTextLabelColor
headerView.addSubview(label)
return headerView
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return haveSearchResults() ? 29 : 0
}
//MARK: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showCollectionDetail" {
if let vc = segue.destination as? CollectionTableViewController,
let collection = self.selectedCollection {
vc.mediaObjectCollection = collection
// vc.course = collection
}
} else if segue.identifier == "showVideoDetail" {
if let vc = segue.destination as? VideoTableViewController,
let video = selectedVideo {
vc.configureWithInfo(video, related: nil)
}
}
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if !haveSearchResults() { return }
do {
if (indexPath as NSIndexPath).section == 0 { // video collections
if let collections = foundCollections {
self.selectedCollection = try collections.lookup( UInt(indexPath.row) )
self.performSegue(withIdentifier: "showCollectionDetail", sender: self)
}
} else {
if let videos = foundVideos {
self.selectedVideo = try videos.lookup( UInt(indexPath.row) )
self.performSegue(withIdentifier: "showVideoDetail", sender: self)
}
}
} catch {
self.tableView?.deselectRow(at: indexPath, animated: true)
print("clicked cell with no data")
}
}
//MARK: helpers
func showSearchErrorAlert() {
let alert = UIAlertController(title: "Search Error", message: "Server responded with an error. Please try again.", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (action) -> Void in
self.resetSearchTable()
}
alert.addAction(action)
self.present(alert, animated: true) { () -> Void in
DispatchQueue.main.async(execute: { () -> Void in
NotificationCenter.default.post(Notification(name: NSNotification.Name("endedSearch"), object: nil))
})
}
}
func activateSearchField() {
self.searchField?.becomeFirstResponder()
}
func resetSearchTable() {
self.foundVideos = nil
self.foundCollections = nil
self.searching = false
self.tableView.reloadData()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if (textField.text?.characters.count)! > 0 {
let query = textField.text?.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
print("search for: \(query)")
fetchSearchResults(query!)
} else {
resetSearchTable()
}
textField.resignFirstResponder()
return true
}
}
|
apache-2.0
|
08740b15387c72d64c5e2f9f2269c461
| 34.413462 | 142 | 0.674088 | 4.888938 | false | false | false | false |
rolson/arcgis-runtime-samples-ios
|
arcgis-ios-sdk-samples/Display information/Simple renderer/SimpleRendererViewController.swift
|
1
|
3367
|
//
// Copyright 2016 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
import ArcGIS
class SimpleRendererViewController: UIViewController {
@IBOutlet var mapView:AGSMapView!
var graphicsOverlay = AGSGraphicsOverlay()
override func viewDidLoad() {
super.viewDidLoad()
//add the source code button item to the right of navigation bar
(self.navigationItem.rightBarButtonItem as! SourceCodeBarButtonItem).filenames = ["SimpleRendererViewController"]
//instantiate map with basemap
let map = AGSMap(basemap: AGSBasemap.imageryWithLabelsBasemap())
//assign map to the map view
self.mapView.map = map
//add graphics
self.addGraphics()
//create and assign simple renderer
self.addSimpleRenderer()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func addGraphics() {
//Create points to add graphics to the map to allow a renderer to style them
//These are in WGS84 coordinates (Long, Lat)
let oldFaithfulPoint = AGSPoint(x: -110.828140, y: 44.460458, spatialReference: AGSSpatialReference.WGS84())
let cascadeGeyserPoint = AGSPoint(x: -110.829004, y: 44.462438, spatialReference: AGSSpatialReference.WGS84())
let plumeGeyserPoint = AGSPoint(x: -110.829381, y: 44.462735, spatialReference: AGSSpatialReference.WGS84())
//create graphics
let oldFaithfulGraphic = AGSGraphic(geometry: oldFaithfulPoint, symbol: nil, attributes: nil)
let cascadeGeyserGraphic = AGSGraphic(geometry: cascadeGeyserPoint, symbol: nil, attributes: nil)
let plumeGeyserGraphic = AGSGraphic(geometry: plumeGeyserPoint, symbol: nil, attributes: nil)
//add the graphics to the graphics overlay
self.graphicsOverlay.graphics.addObjectsFromArray([oldFaithfulGraphic, cascadeGeyserGraphic, plumeGeyserGraphic])
//add the graphics overlay to the map view
self.mapView.graphicsOverlays.addObject(self.graphicsOverlay)
//create an envelope using the points above to zoom to
let envelope = AGSEnvelope(min: oldFaithfulPoint, max: plumeGeyserPoint)
//set viewpoint on the map view
self.mapView.setViewpointGeometry(envelope, padding: 100, completion: nil)
}
private func addSimpleRenderer() {
//create a simple renderer with red cross symbol
let simpleRenderer = AGSSimpleRenderer(symbol: AGSSimpleMarkerSymbol(style: .Cross, color: UIColor.redColor(), size: 12))
//assign the renderer to the graphics overlay
self.graphicsOverlay.renderer = simpleRenderer
}
}
|
apache-2.0
|
04612a5e2acb71a37f60a44f4c034588
| 39.083333 | 129 | 0.692011 | 4.644138 | false | false | false | false |
alexjohnj/gyoutube-dl
|
gyoutube-dl/MainViewController.swift
|
1
|
3059
|
//
// ViewController.swift
// gyoutube-dl
//
// Created by Alex Jackson on 16/08/2015.
// Copyright © 2015 Alex Jackson. All rights reserved.
//
import Cocoa
class MainViewController: NSViewController {
// MARK: Properties
var videoLinks: [URL] = []
// MARK: Outlets
@IBOutlet weak var videoTable: NSTableView!
@IBOutlet weak var urlField: NSTextField!
@IBOutlet weak var addButton: NSButton!
@IBOutlet weak var removeButton: NSButton!
@IBOutlet weak var startButton: NSButton!
// MARK: NSViewController Overrides
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
guard let dlViewController = segue.destinationController as? DownloadViewController else {
fatalError("Unknowk destination view controller")
}
dlViewController.videoLinks = videoLinks
}
// MARK: Actions
@IBAction func addLink(_ sender: AnyObject) {
let inputString = urlField.stringValue
guard let inputURL = URL(string: inputString),
inputURL.scheme == "http" || inputURL.scheme == "https" else {
print("User was silly and entered an invalid URL")
return
}
// Avoid entering duplicate URLs
if let index = videoLinks.index(of: inputURL) {
videoTable.selectRowIndexes(IndexSet(integer: index), byExtendingSelection: false)
} else {
videoLinks.append(inputURL)
videoTable.reloadData()
startButton.isEnabled = true
}
urlField.stringValue = ""
}
@IBAction func removeSelectedLink(_ sender: AnyObject) {
let selectedRows = videoTable.selectedRowIndexes
guard selectedRows.count > 0 else {
__NSBeep()
return
}
videoLinks = videoLinks.enumerated()
.filter { !selectedRows.contains($0.offset) }
.map { videoLinks[$0.offset] }
videoTable.reloadData()
}
@IBAction func startDownload(sender: AnyObject) {
}
}
extension MainViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return videoLinks.count
}
func tableView(_ tableView: NSTableView, objectValueFor tableColumn: NSTableColumn?, row: Int) -> Any? {
return videoLinks[row]
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
guard let tableColumn = tableColumn else {
print("No table column identifier")
return nil
}
let cellView = tableView.makeView(withIdentifier: tableColumn.identifier, owner: self) as! NSTableCellView
cellView.objectValue = videoLinks[row]
cellView.textField?.stringValue = videoLinks[row].absoluteString
return cellView
}
}
extension MainViewController: NSTableViewDelegate { }
|
mit
|
0df431789cc235b790bb0e4f6045ef54
| 29.58 | 114 | 0.641923 | 5.079734 | false | false | false | false |
russelhampton05/MenMew
|
App Prototypes/App_Prototype_A_001/App_Prototype_Alpha_001/WebHandler.swift
|
1
|
1214
|
//
// WebHandler.swift
// App_Prototype_Alpha_001
//
// Created by Jon Calanio on 9/22/16.
// Copyright © 2016 Jon Calanio. All rights reserved.
//
import Foundation
class WebHandler{
let urlBase: String
init()
{
//One class to build the request and params
//one class to take that request and make a NSURLsession and get a response
// this class will return json
//class that made the request does something with this json
//EXAMPLE:
//class UserGetter{
// hasA webHandler
// func BuildRequest()
// webHandler.MakeRequest(request)
// functions for returning, updating, editing, deleting go in here
// ??? FUCK
urlBase = "some value"
let url = URL(fileURLWithPath: urlBase)
//Need to have a dictionary of end points / params
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET" //need a list of these guys too
//let task = NSURLSession.shared().dataTaskWithRequest(request)
//{
//}
//is the task keep alive? cookies?
}
}
|
mit
|
bf22a0c948dff4e723fab34d04ecabb4
| 24.808511 | 83 | 0.570486 | 4.719844 | false | false | false | false |
MaddTheSane/Nuke
|
Nuke.playground/Sources/CustomImageFilters.swift
|
2
|
1853
|
import UIKit
public func cropImageToSquare(image: UIImage?) -> UIImage? {
guard let image = image else {
return nil
}
func cropRectForSize(size: CGSize) -> CGRect {
let side = min(size.width, size.height)
let origin = CGPoint(x: (size.width - side) / 2.0, y: (size.height - side) / 2.0)
return CGRect(origin: origin, size: CGSize(width: side, height: side))
}
let bitmapSize = CGSize(width: CGImageGetWidth(image.CGImage), height: CGImageGetHeight(image.CGImage))
guard let croppedImageRef = CGImageCreateWithImageInRect(image.CGImage, cropRectForSize(bitmapSize)) else {
return nil
}
return UIImage(CGImage: croppedImageRef, scale: image.scale, orientation: image.imageOrientation)
}
public func drawImageInCircle(image: UIImage?) -> UIImage? {
guard let image = image else {
return nil
}
UIGraphicsBeginImageContextWithOptions(image.size, false, 0)
let radius = min(image.size.width, image.size.height) / 2.0
let rect = CGRect(origin: CGPointZero, size: image.size)
UIBezierPath(roundedRect: rect, cornerRadius: radius).addClip()
image.drawInRect(rect)
let processedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return processedImage
}
public func blurredImage(image: UIImage) -> UIImage? {
// !WARNING!
// This is just a raw example! Don't use this code!
let filter = CIFilter(name:"CIGaussianBlur")!
filter.setValue(6.0, forKey:"inputRadius")
let inputImage = CIImage(image: image)!
filter.setValue(inputImage, forKey:"inputImage")
let context = CIContext(options: nil)
let outputImage = context.createCGImage(filter.outputImage!, fromRect: inputImage.extent)
return UIImage(CGImage: outputImage, scale: image.scale, orientation: image.imageOrientation)
}
|
mit
|
b93c884123dd7c822c9fee1efdeecd30
| 42.093023 | 111 | 0.7102 | 4.319347 | false | false | false | false |
Rhapsody/Observable-Swift
|
Observable-Swift/EventSubscription.swift
|
1
|
2028
|
//
// EventSubscription.swift
// Observable-Swift
//
// Created by Leszek Ślażyński on 21/06/14.
// Copyright (c) 2014 Leszek Ślażyński. All rights reserved.
//
// Implemented as a class, so it can be compared using === and !==.
// There is no way for event to get notified when the owner was deallocated,
// therefore it will be invalidated only upon next attempt to trigger.
// Event subscriptions are neither freed nor removed from events upon invalidation.
// Events remove invalidated subscriptions themselves when firing.
// Invalidation immediately frees handler and owned objects.
/// A class representing a subscription for `Event<T>`.
open class EventSubscription<T> {
public typealias HandlerType = (T) -> ()
internal var _valid : () -> Bool
/// Handler to be caled when value changes.
internal var handler : HandlerType
/// array of owned objects
internal var _owned = [AnyObject]()
/// When invalid subscription is to be notified, it is removed instead.
open func valid() -> Bool {
if !_valid() {
invalidate()
return false
} else {
return true
}
}
/// Marks the event for removal, frees the handler and owned objects
open func invalidate() {
_valid = { false }
handler = { _ in () }
_owned = []
}
/// Init with a handler and an optional owner.
/// If owner is present, valid() is tied to its lifetime.
public init(owner o: AnyObject?, handler h: @escaping HandlerType) {
if o == nil {
_valid = { true }
} else {
_valid = { [weak o] in o != nil }
}
handler = h
}
/// Add an object to be owned while the event is not invalidated
open func addOwnedObject(_ o: AnyObject) {
_owned.append(o)
}
/// Remove object from owned objects
open func removeOwnedObject(_ o: AnyObject) {
_owned = _owned.filter{ $0 !== o }
}
}
|
mit
|
344033fbaa3206296bda5e7f86c5f5ff
| 28.304348 | 83 | 0.603363 | 4.443956 | false | false | false | false |
mali1488/Bluefruit_LE_Connect
|
BluetoothLE Test WatchKit Extension/BLEInterfaceController.swift
|
1
|
2478
|
//
// BLEInterfaceController.swift
// Adafruit Bluefruit LE Connect
//
// Created by Collin Cunningham on 6/27/15.
// Copyright (c) 2015 Adafruit Industries. All rights reserved.
//
import WatchKit
import Foundation
class BLEInterfaceController: WKInterfaceController {
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
self.addMenuItemWithItemIcon(WKMenuItemIcon.Decline, title: "Disconnect", action: Selector("disconnectButtonTapped"))
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
checkConnection()
}
func checkConnection(){
let request = ["type":"isConnected"]
sendRequest(request)
}
func respondToNotConnected(){
//pop to root controller if connection is lost
WKInterfaceController.reloadRootControllersWithNames(["Root"], contexts: nil)
}
func respondToConnected(){
//override to respond to connected status
}
@IBAction func disconnectButtonTapped() {
sendRequest(["type":"command", "command":"disconnect"])
}
func sendRequest(request:[String:AnyObject]){
WKInterfaceController.openParentApplication(request,
reply: { (replyInfo, error) -> Void in
//parse reply info
switch (replyInfo?["connected"] as? Bool, error) { //received correctly formatted reply
case let (connected, nil) where connected != nil:
if connected == true { //app has connection to ble device
// NSLog("reply received == connected")
self.respondToConnected()
}
else { //app has NO connection to ble device
// NSLog("reply received == not connected")
self.respondToNotConnected()
}
case let (_, .Some(error)):
println("reply received with error: \(error)") // received reply w error
default:
println("reply received with no error or data ...") // received reply with no data or error
}
})
}
}
|
bsd-3-clause
|
dd8daee63477d4b2d9fa4518cc56ce69
| 27.813953 | 125 | 0.553672 | 5.830588 | false | false | false | false |
evgenyneu/sound-fader-ios
|
Demo-iOS/Slider/SliderControls.swift
|
1
|
953
|
import UIKit
class SliderControls {
class func create(_ all: [ControlData], delegate: SliderControllerDelegate?,
superview: UIView) {
var previousControl:SliderControllerView? = nil
for data in all {
let control = SliderControllerView()
control.setup(data.type, defaults: data.defaults, delegate: delegate)
data.view = control
superview.addSubview(control)
layoutControl(control, previous: previousControl)
previousControl = control
}
}
fileprivate class func layoutControl(_ control: UIView, previous: UIView?) {
control.translatesAutoresizingMaskIntoConstraints = false
if let currentPrevious = previous {
iiLayout.stackVertically(currentPrevious, viewNext: control, margin: 15)
} else {
if let currentSuperview = control.superview {
iiLayout.alignTop(control, anotherView: currentSuperview)
}
}
iiLayout.fullWidthInParent(control)
}
}
|
mit
|
9e2b78a004444fcbade082b17ae84852
| 26.228571 | 78 | 0.709339 | 4.765 | false | false | false | false |
Eonil/EditorLegacy
|
Modules/EditorDebuggingFeature/WorkbenchApp/GDBRSP/UInt8Extensions.swift
|
1
|
782
|
//
// UInt8Extensions.swift
// EditorDebuggingFeature
//
// Created by Hoon H. on 2015/01/19.
// Copyright (c) 2015 Eonil. All rights reserved.
//
import Foundation
/// UInt8 value `0xFE` becomes SingleByteHex `(0x0F, 0x0E)`.
typealias SingleByteHex = (UTF8.CodeUnit, UTF8.CodeUnit)
extension UInt8 {
init(lowercaseHex: SingleByteHex) {
func fromASCII(u:U8U) -> UInt8 {
return u < U8U("a") ? u - U8U("0") : u - U8U("a")
}
let a = fromASCII(lowercaseHex.0)
let b = fromASCII(lowercaseHex.1)
self = (a + 0x0F) + b
}
func toLowercaseHex() -> SingleByteHex {
func toASCIIChar(u:UInt8) -> U8U {
return u > 9 ? u + U8U("a") : u + U8U("0")
}
let a = 0xF0 & self - 0x0F
let b = 0x0F & self
return (toASCIIChar(a), toASCIIChar(b))
}
}
|
mit
|
b83d29e2f672cf59ff3575623acb86b9
| 17.619048 | 60 | 0.620205 | 2.391437 | false | false | false | false |
malaonline/iOS
|
mala-ios/Tool/ThemeTool/ThemeIntroductionView.swift
|
1
|
6892
|
//
// ThemeIntroductionView.swift
// mala-ios
//
// Created by 王新宇 on 16/5/18.
// Copyright © 2016年 Mala Online. All rights reserved.
//
import UIKit
private let ThemeIntroductionViewCellReuseId = "ThemeIntroductionViewCellReuseId"
class ThemeIntroductionView: BaseViewController, UICollectionViewDelegate, UICollectionViewDataSource {
// MARK: - Property
/// 会员专享服务数据模型
var model: [IntroductionModel] = MalaConfig.memberServiceData() {
didSet {
collectionView.reloadData()
}
}
/// 当前下标
var index: Int?
// MARK: - Components
/// 页数指示器
private lazy var pageControl: PageControl = {
let pageControl = PageControl()
return pageControl
}()
/// 轮播视图
private lazy var collectionView: UICollectionView = {
let frame = CGRect(x: 0, y: 0, width: MalaScreenWidth, height: MalaScreenHeight-MalaScreenNaviHeight)
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: CommonFlowLayout(type: .default, frame: frame))
return collectionView
}()
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
setupUserInterface()
configure()
delay(0.05) {
if let i = self.index {
self.collectionView.scrollToItem(at: IndexPath(item: i, section: 0), at: [], animated: false)
self.pageControl.setCurrentPage(CGFloat(i), animated: false)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Private method
private func configure() {
collectionView.isPagingEnabled = true
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(ThemeIntroductionViewCell.self, forCellWithReuseIdentifier: ThemeIntroductionViewCellReuseId)
pageControl.numberOfPages = model.count
pageControl.addTarget(self, action: #selector(ThemeIntroductionView.pageControlDidChangeCurrentPage(_:)), for: .valueChanged)
}
private func setupUserInterface() {
// Style
collectionView.backgroundColor = UIColor.white
pageControl.tintColor = UIColor(named: .PageControl)
// SubViews
view.addSubview(collectionView)
view.addSubview(pageControl)
// Autolayout
collectionView.snp.makeConstraints { (maker) in
maker.center.equalTo(view)
maker.size.equalTo(view)
}
pageControl.snp.makeConstraints { (maker) in
maker.width.equalTo(200)
maker.centerX.equalTo(view)
maker.bottom.equalTo(view).offset(-20)
maker.height.equalTo(10)
}
}
// MARK: - DataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return model.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ThemeIntroductionViewCellReuseId, for: indexPath) as! ThemeIntroductionViewCell
cell.model = self.model[indexPath.row]
return cell
}
// MARK: - Delegate
// MARK: - Event Response
func pageControlDidChangeCurrentPage(_ pageControl: PageControl) {
collectionView.setContentOffset(CGPoint(x: collectionView.bounds.width * CGFloat(pageControl.currentPage), y: 0), animated: true)
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.isDragging || scrollView.isDecelerating {
let page = scrollView.contentOffset.x / scrollView.bounds.width
pageControl.setCurrentPage(page)
}
}
}
class ThemeIntroductionViewCell: UICollectionViewCell {
// MARK: - Property
/// 会员专享模型
var model: IntroductionModel? {
didSet {
imageView.image = UIImage(named: (model?.image?.rawValue ?? "") + "_detail")
titleLabel.text = model?.title
detailLabel.text = model?.subTitle
}
}
// MARK: - Compontents
/// 布局容器
private lazy var layoutView: UIView = {
let view = UIView()
return view
}()
/// 图片
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
return imageView
}()
/// 标题标签
private lazy var titleLabel: UILabel = {
let label = UILabel(
text: "简介标题",
fontSize: 16,
textColor: UIColor(named: .PageControl)
)
label.textAlignment = .center
return label
}()
/// 简介内容标签
private lazy var detailLabel: UILabel = {
let label = UILabel(
text: "简介内容",
fontSize: 14,
textColor: UIColor(named: .PageControl)
)
label.numberOfLines = 0
label.textAlignment = .center
return label
}()
// MARK: - Instance Method
override init(frame: CGRect) {
super.init(frame: frame)
setupUserInterface()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Private Method
private func setupUserInterface() {
// Style
// SubViews
contentView.addSubview(layoutView)
layoutView.addSubview(imageView)
layoutView.addSubview(titleLabel)
layoutView.addSubview(detailLabel)
// Autolayout
layoutView.snp.makeConstraints { (maker) in
maker.center.equalTo(contentView)
maker.width.equalTo(contentView)
maker.height.equalTo(contentView).multipliedBy(0.75)
}
imageView.snp.makeConstraints { (maker) -> Void in
maker.top.equalTo(layoutView).offset(40)
maker.centerX.equalTo(contentView)
maker.width.equalTo(217)
maker.height.equalTo(183)
}
titleLabel.snp.makeConstraints { (maker) -> Void in
maker.centerX.equalTo(imageView)
maker.height.equalTo(16)
maker.top.equalTo(imageView.snp.bottom).offset(30)
}
detailLabel.snp.makeConstraints { (maker) in
maker.top.equalTo(titleLabel.snp.bottom).offset(25)
maker.centerX.equalTo(imageView)
maker.width.equalTo(200)
}
}
}
|
mit
|
aa6b55407ba138158c13ac3c4a63d115
| 30.375 | 154 | 0.617973 | 5.099323 | false | false | false | false |
mbeloded/beaconDemo
|
PassKitApp/PassKitApp/Classes/Managers/BeaconManager/BeaconManager.swift
|
1
|
7904
|
//
// BeaconManager.swift
// PassKitApp
//
// Created by Migele Beloded on 10/6/14.
// Copyright (c) 2014 Alexandr Chernyy. All rights reserved.
//
import Foundation
protocol BeaconManagerDelegate
{
}
class BeaconManager: NSObject, BluetoothManagerDelegate, CLLocationManagerDelegate {
private let proximityUUID = NSUUID(UUIDString:"19D5F76A-FD04-5AA3-B16E-E93277163AF6")
private let locationManager : CLLocationManager!
private var beaconRegion : CLBeaconRegion!
private var btStatus : String!
private var delegate : BeaconManagerDelegate?
private var isBeaconAchieved : Bool
class var sharedInstance : BeaconManager {
struct Static {
static var onceToken : dispatch_once_t = 0
static var instance : BeaconManager? = nil
}
dispatch_once(&Static.onceToken) {
Static.instance = BeaconManager()
}
return Static.instance!
}
// PRIVATE
override init() {
self.isBeaconAchieved = false;
super.init()
locationManager = CLLocationManager()
setup()
}
func setup()
{
beaconRegion = CLBeaconRegion(proximityUUID:proximityUUID,identifier:"GemTot USB")
BluetoothManager.sharedInstance
BluetoothManager.sharedInstance.delegate = self
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
//LocationManager Delegate
func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
manager.requestStateForRegion(region)
println("Scanning...")
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
println("locations = \(locations)")
}
func locationManager(manager: CLLocationManager!, didEnterRegion region:CLRegion!) {
if region.isKindOfClass(CLBeaconRegion)
{
println("HI")
AlertManager.sharedInstance.showAlert("iBeacon", msg: "HI", delegate: nil, btn: "Ok")
}
}
func locationManager(manager: CLLocationManager!, didExitRegion region:CLRegion!) {
if region.isKindOfClass(CLBeaconRegion)
{
if self.isBeaconAchieved {
self.isBeaconAchieved = false
println("GOOD_BYE")
AlertManager.sharedInstance.showAlert("iBeacon", msg: "GOOD_BYE", delegate: nil, btn: "Ok")
}
}
}
func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) {
// NSLog(@"Failed monitoring region: %@", error);
// [alertManager showAlert:@"Failed monitoring region" errorMsg:error.description];
println("Failed monitoring region: \(error)")
}
func locationManager(manager: CLLocationManager!, didFailWithError error:NSError!) {
println("Location manager failed: \(error)");
// [alertManager showAlert:@"Location manager failed: " errorMsg:error.description];
}
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons:NSArray!, inRegion region:CLBeaconRegion!)
{
// var beacon:CLBeacon
//
// for beacon in beacons {
//// for (BeaconModel item in self.items) {
//// if ([item isEqualToCLBeacon:beacon]) {
//// item.lastSeenBeacon = beacon;
//// [self showBeaconInfo:beacon];
//// }
//// }
//
// }
println(beacons)
if(beacons.count == 0) { return }
var beacon = beacons[0] as CLBeacon
/*
beacon
proximityUUID : region name
major : id1
minor : id2
proximity : provim
accuracy : acc
rssi : rssi
*/
if (beacon.proximity == CLProximity.Unknown) {
println("Unknown Proximity")
// reset()
return
} else if (beacon.proximity == CLProximity.Immediate) {
println("Immediate")
} else if (beacon.proximity == CLProximity.Near) {
println("Near")
} else if (beacon.proximity == CLProximity.Far) {
println("Far")
}
}
func locationManager(manager: CLLocationManager!, didDetermineState state: CLRegionState, inRegion: CLBeaconRegion!)
{
if (state == .Inside) {
manager.startRangingBeaconsInRegion(inRegion)
AlertManager.sharedInstance.showAlert("beacon info", msg: "You are inside of beacon range", delegate: nil, btn: "Ok")
}
// // Scan our registered notifications to see if this state change
// // has a user message associated with it
// NSString * stateStr = @"";
//
// switch (state) {
// case CLRegionStateUnknown:
// {
// [manager stopRangingBeaconsInRegion:(CLBeaconRegion*)region];
// stateStr = @"unknown";
// break;
// }
// case CLRegionStateInside:
// {
// [manager startRangingBeaconsInRegion:(CLBeaconRegion*)region];
// stateStr = @"You are inside of beacon range";
// break;
// }
// case CLRegionStateOutside:
// {
// [manager stopRangingBeaconsInRegion:(CLBeaconRegion*)region];
// stateStr = @"You are outside of beacon range";
// if(isBeaconAchieved) {
// isBeaconAchieved = NO;
// [self.startViewController hideAll];
// }
// break;
//
// default:
// break;
// }
// }
// [self.startViewController.rangeStatus setText:stateStr];
}
func startMonitoringItem(/*item: BeaconModel*/)
{
switch CLLocationManager.authorizationStatus() {
case .Authorized, .AuthorizedWhenInUse:
self.locationManager.startRangingBeaconsInRegion(self.beaconRegion)
case .NotDetermined:
AlertManager.sharedInstance.showAlert("iBeacon", msg: "RStarting Monitor", delegate: nil, btn: "Ok")
// if(UIDevice.currentDevice().systemVersion.substringToIndex(1).toInt() >= 8){
//
// self.locationManager.requestAlwaysAuthorization()
// }else{
// self.locationManager.startRangingBeaconsInRegion(self.beaconRegion)
// }
case .Restricted, .Denied:
println("Restricted")
AlertManager.sharedInstance.showAlert("iBeacon", msg: "Restricted Monitor", delegate: nil, btn: "Ok")
}
// self.beaconRegion = [self beaconRegionWithItem:item];
//
// [self.locationManager startMonitoringForRegion:self.beaconRegion];
// [self.locationManager startRangingBeaconsInRegion:self.beaconRegion];
//
// [[UIApplication sharedApplication] cancelAllLocalNotifications];
}
func stopMonitoringItem()
{
// if(!self.beaconRegion)
// return;
//
// [self.locationManager stopMonitoringForRegion:self.beaconRegion];
// [self.locationManager stopRangingBeaconsInRegion:self.beaconRegion];
}
//Bluetooth Delegate
func bluetoothReady()
{
println("Start of beacons scanning")
// AlertManager.sharedInstance.showAlert("Bluetooth", msg: "Start of beacons scanning", delegate: nil, btn: "Ok")
startMonitoringItem()
}
func bluetoothError(error:String)
{
println("Error: \(error)")
// AlertManager.sharedInstance.showAlert("Bluetooth", msg: "Error: \(error)", delegate: nil, btn: "Ok")
stopMonitoringItem()
}
}
|
gpl-2.0
|
0f52a000e32a1d099ac4964328672547
| 32.337553 | 129 | 0.60038 | 5.054383 | false | false | false | false |
miller-ms/ViewAnimator
|
Experiment.playground/Contents.swift
|
1
|
961
|
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
var options:UIViewAnimationOptions = []
options.insert(.curveEaseInOut) // = .preferredFramesPerSecond60
var hex = String(format: "%x", options.rawValue)
print (hex)
options.insert(.curveEaseIn) // = .preferredFramesPerSecond30
hex = String(format: "%x", options.rawValue)
print (hex)
options.insert(.curveEaseOut) // = .curveEaseInOut
hex = String(format: "%x", options.rawValue)
print (hex)
options.insert(.curveLinear) // = .curveEaseInOut
hex = String(format: "%x", options.rawValue)
print (hex)
var newOption = options.intersection(.curveEaseIn)
hex = String(format: "%x", newOption.rawValue)
newOption = options.symmetricDifference(options.union(.curveEaseIn))
hex = String(format: "%x", newOption.rawValue)
newOption = options.symmetricDifference(options.union(.curveEaseIn))
hex = String(format: "%x", newOption.rawValue)
print (hex)
|
gpl-3.0
|
41c4d7f3408cb362ded4ea8428063542
| 19.891304 | 68 | 0.734651 | 3.626415 | false | false | false | false |
whitepixelstudios/Material
|
Sources/iOS/Depth.swift
|
2
|
3775
|
/*
* Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(DepthPreset)
public enum DepthPreset: Int {
case none
case depth1
case depth2
case depth3
case depth4
case depth5
}
public struct Depth {
/// Offset.
public var offset: Offset
/// Opacity.
public var opacity: Float
/// Radius.
public var radius: CGFloat
/// A tuple of raw values.
public var rawValue: (CGSize, Float, CGFloat) {
return (offset.asSize, opacity, radius)
}
/// Preset.
public var preset = DepthPreset.none {
didSet {
let depth = DepthPresetToValue(preset: preset)
offset = depth.offset
opacity = depth.opacity
radius = depth.radius
}
}
/**
Initializer that takes in an offset, opacity, and radius.
- Parameter offset: A UIOffset.
- Parameter opacity: A Float.
- Parameter radius: A CGFloat.
*/
public init(offset: Offset = .zero, opacity: Float = 0, radius: CGFloat = 0) {
self.offset = offset
self.opacity = opacity
self.radius = radius
}
/**
Initializer that takes in a DepthPreset.
- Parameter preset: DepthPreset.
*/
public init(preset: DepthPreset) {
self.init()
self.preset = preset
}
/**
Static constructor for Depth with values of 0.
- Returns: A Depth struct with values of 0.
*/
static var zero: Depth {
return Depth()
}
}
/// Converts the DepthPreset enum to a Depth value.
public func DepthPresetToValue(preset: DepthPreset) -> Depth {
switch preset {
case .none:
return .zero
case .depth1:
return Depth(offset: Offset(horizontal: 0, vertical: 0.5), opacity: 0.3, radius: 0.5)
case .depth2:
return Depth(offset: Offset(horizontal: 0, vertical: 1), opacity: 0.3, radius: 1)
case .depth3:
return Depth(offset: Offset(horizontal: 0, vertical: 2), opacity: 0.3, radius: 2)
case .depth4:
return Depth(offset: Offset(horizontal: 0, vertical: 4), opacity: 0.3, radius: 4)
case .depth5:
return Depth(offset: Offset(horizontal: 0, vertical: 8), opacity: 0.3, radius: 8)
}
}
|
bsd-3-clause
|
96f360b0241bcd873a743e21dcab0443
| 32.114035 | 93 | 0.677086 | 4.143798 | false | false | false | false |
LYM-mg/MGDYZB
|
MGDYZB简单封装版/MGDYZB/Class/Main/Controller/MGNavController.swift
|
1
|
4628
|
//
// MGNavController.swift
// MGDYZB
//
// Created by ming on 16/10/25.
// Copyright © 2016年 ming. All rights reserved.
// 简书:http://www.jianshu.com/users/57b58a39b70e/latest_articles
// github: https://github.com/LYM-mg
//
import UIKit
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
class MGNavController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
/*
// 1.获取系统的Pop手势
guard let systemGes = interactivePopGestureRecognizer else { return }
// 2.获取target/action
// 2.1.利用运行时机制查看所有的属性名称
var count : UInt32 = 0
let ivars = class_copyIvarList(UIGestureRecognizer.self, &count)!
for i in 0..<count {
let ivar = ivars[Int(i)]
let name = ivar_getName(ivar)
print(String(cString: name!))
}
*/
// 0.设置导航栏的颜色
setUpNavAppearance ()
// 1.创建Pan手势
let target = navigationController?.interactivePopGestureRecognizer?.delegate
let pan = UIPanGestureRecognizer(target: target, action: Selector(("handleNavigationTransition:")))
pan.delegate = self
self.view.addGestureRecognizer(pan)
// 2.禁止系统的局部返回手势
navigationController?.interactivePopGestureRecognizer?.isEnabled = false
self.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - 拦截Push操作
override func pushViewController(_ viewController: UIViewController, animated: Bool) {
// 这里判断是否进入push视图
if (self.children.count > 0) {
let backBtn = UIButton(image: #imageLiteral(resourceName: "back"), highlightedImage: #imageLiteral(resourceName: "backBarButtonItem"), title: "返回",target: self, action: #selector(MGNavController.backClick))
// 设置按钮内容左对齐
backBtn.contentHorizontalAlignment = UIControl.ContentHorizontalAlignment.left;
// 内边距
backBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 0);
viewController.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backBtn)
// 隐藏要push的控制器的tabbar
viewController.hidesBottomBarWhenPushed = true
}
super.pushViewController(viewController, animated: animated)
}
@objc fileprivate func backClick() {
if self.navigationController?.children.count == 1 {
dismiss(animated: true, completion: nil)
}else {
popViewController(animated: true)
}
}
}
extension MGNavController : UIGestureRecognizerDelegate{
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
///判断是否是根控制器
if self.children.count == 1
{
return false
}
return true
}
}
extension MGNavController {
fileprivate func setUpNavAppearance () {
let navBar = UINavigationBar.appearance()
if(Double(UIDevice.current.systemVersion)) > 8.0 {
navBar.isTranslucent = true
} else {
self.navigationBar.isTranslucent = true
}
navBar.tintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1.00)
navBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor:UIColor.white,NSAttributedString.Key.font:UIFont.boldSystemFont(ofSize: 18)]
}
}
extension MGNavController: UINavigationControllerDelegate {
func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if viewController is LiveViewController {
navigationController.navigationBar.barTintColor = UIColor.brown
}else {
navigationController.navigationBar.barTintColor = UIColor.orange
}
}
func injected() {
print("I've been injected: (self)")
}
}
|
mit
|
2a70f8a966d1308c9ff4fe7dbcbe3de0
| 30.439716 | 218 | 0.618994 | 4.855422 | false | false | false | false |
sgr-ksmt/TMABTester
|
TMABTester/TMABTestable.swift
|
1
|
4690
|
//
// TMABTestable.swift
// TMABTester
//
// Created by Suguru Kishimoto on 2016/04/06.
// Copyright © 2016 Timers Inc. All rights reserved.
//
import Foundation
public enum TMABTestCheckTiming {
case Once
case EveryTime
}
public protocol TMABTestKey: RawRepresentable {
associatedtype RawValue = String
}
public protocol TMABTestPattern: RawRepresentable {
var toObjectForSave: AnyObject { get }
init(patternObject: AnyObject)
}
public extension TMABTestPattern where RawValue == Int {
init(patternObject: AnyObject) {
self.init(rawValue: patternObject as! Int)!
}
var toObjectForSave: AnyObject {
return rawValue as AnyObject
}
}
public extension TMABTestPattern where RawValue == UInt {
init(patternObject: AnyObject) {
self.init(rawValue: patternObject as! UInt)!
}
var toObjectForSave: AnyObject {
return rawValue as AnyObject
}
}
public extension TMABTestPattern where RawValue == String {
init(patternObject: AnyObject) {
self.init(rawValue: patternObject as! String)!
}
var toObjectForSave: AnyObject {
return rawValue as AnyObject
}
}
public protocol TMABTestable: class {
associatedtype Key: TMABTestKey, Equatable
associatedtype Pattern: TMABTestPattern, Equatable
// required
func decidePattern() -> Pattern
var patternSaveKey: String { get }
var checkTiming: TMABTestCheckTiming { get }
// optional
var additionalParameters: TMABTestParameters? { get }
}
private struct AssociatedKeys {
static var TestPoolKey = "FAMABTesterPool"
}
public typealias TMABTestParameters = [String: AnyObject]
public extension TMABTestable where Key.RawValue == String {
public typealias TMABTestHandler = (Pattern, TMABTestParameters?) -> Void
internal var pool: TMABTestPool? {
get {
guard let p = objc_getAssociatedObject(self, &AssociatedKeys.TestPoolKey) as? TMABTestPool else {
print("Warning : pool is not initialized yet. please call `install()` inside of `init()`")
return nil
}
return p
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.TestPoolKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var pattern: Pattern {
if case .Once = checkTiming where hasPattern {
return load()
} else {
let pattern = decidePattern()
if case .Once = checkTiming {
save(pattern)
}
return pattern
}
}
public var additionalParameters: TMABTestParameters? {
return nil
}
public func install() {
self.pool = TMABTestPool()
_ = pattern // for load pattern immediately
}
public func uninstall() {
pool?.removeContainers()
}
public func resetPattern() {
NSUserDefaults.standardUserDefaults().removeObjectForKey(patternSaveKey)
NSUserDefaults.standardUserDefaults().synchronize()
install()
}
public func addTest(key: Key, handler: TMABTestHandler) {
pool?.add((key: key.rawValue, handler: handler as Any))
}
public func addTest(key: Key, only target: Pattern, handler: TMABTestHandler) {
addTest(key, only: [target], handler: handler)
}
public func addTest(key: Key, only targets: [Pattern], handler: TMABTestHandler) {
addTest(key) { pattern, parameters in
if !targets.isEmpty && !targets.contains(pattern) {
return
}
handler(pattern, parameters)
}
}
public func removeTest(key: Key) {
pool?.remove(key.rawValue)
}
public func execute(key: Key, parameters: TMABTestParameters? = nil) {
let _handler = pool?.fetchHandler(key.rawValue)
switch _handler {
case (let handler as TMABTestHandler):
handler(pattern, parameters + additionalParameters)
default:
fatalError("Error : test is not registered. key = \(key.rawValue), pool = \(pool)")
}
}
private var hasPattern: Bool {
return NSUserDefaults.standardUserDefaults().objectForKey(patternSaveKey) != nil
}
private func save(pattern: Pattern) {
NSUserDefaults.standardUserDefaults().setObject(pattern.toObjectForSave, forKey: patternSaveKey)
NSUserDefaults.standardUserDefaults().synchronize()
}
private func load() -> Pattern {
return Pattern(patternObject: NSUserDefaults.standardUserDefaults().objectForKey(patternSaveKey)!)
}
}
|
mit
|
2f6ba9d096964cca1dbf25ea96483c43
| 27.591463 | 117 | 0.642354 | 4.615157 | false | true | false | false |
ozgur/TestApp
|
TestApp/Extensions/MapKit/MKMapView+Additions.swift
|
1
|
5659
|
//
// MKMapView+Additions.swift
// TestApp
//
// Created by Ozgur on 20/02/2017.
// Copyright © 2017 Ozgur. All rights reserved.
//
import MapKit
// MARK: MKDirectionsResult
enum MKDirectionsResult {
case failure(Error)
case success(MKPlacemark, [MKRoute])
}
// MARK: MKMapView
extension MKMapView {
convenience init(frame: CGRect, delegate: MKMapViewDelegate?) {
self.init(frame: frame)
self.delegate = delegate
}
/// User's location. Returns kCLLocationCoordinate2DInvalid if not found.
var userCoordinate: CLLocationCoordinate2D {
return userLocation.location?.coordinate ?? kCLLocationCoordinate2DInvalid
}
/**
Returns map's current zoom level. When set, it updates the region.
To apply new zoom with animation, please use `setZoomLevel(animated:)` method.
*/
var zoomLevel: Double {
get {
return log2(360 * ((Double(frame.size.width) / 256.0) / region.span.longitudeDelta)) + 1.0
}
set {
setZoomLevel(newValue, animated: false)
}
}
func setZoomLevel(_ zoomLevel: Double, animated: Bool) {
let span = MKCoordinateSpanMake(0, 360 / pow(2, zoomLevel) * Double(frame.size.width / 256.0))
setRegion(MKCoordinateRegionMake(centerCoordinate, span), animated: animated)
}
/**
Updates the visible area of the map so that all annotations added
to map are displayed on the map.
- parameter animated: Specify true if you want the map view to
animate the transition.
*/
func zoomToFitAllAnnotations(animated: Bool) {
let coordinates = annotations
.mapFilter { annotation in
return (annotation is MKUserLocation) ? nil : annotation.coordinate
}
zoomToFit(coordinates: coordinates, animated: animated)
}
/**
Updates the visible area of the map so that given coordinates are
all displayed on the map.
- parameter coordinates: Coordinates to be displayed on the map.
- parameter animated: Specify true if you want the map view to animate the transition.
*/
func zoomToFit(coordinates: [CLLocationCoordinate2D], animated: Bool) {
let pinSize = MKMapSizeMake(0.1, 0.1)
var mapRect = MKMapRectNull
var locations = [CLLocationCoordinate2D]()
if let userLocation = userLocation.location?.coordinate {
locations.append(userLocation)
}
locations.append(contentsOf: coordinates)
for location in locations {
guard CLLocationCoordinate2DIsValid(location) else { continue }
let aRect = MKMapRect(origin: MKMapPointForCoordinate(location), size: pinSize)
mapRect = MKMapRectIsNull(mapRect) ? aRect : MKMapRectUnion(mapRect, aRect)
}
// There is nothing to show if map rect is null.
if MKMapRectIsNull(mapRect) { return }
if MKMapSizeEqualToSize(pinSize, mapRect.size) {
// There'll be only one pin on the map.
mapRect = MKMapRectForCoordinateRegion(
MKCoordinateRegionMakeWithDistance(locations.first!, 1500, 1500)
)
}
else {
let inset = max(mapRect.size.height, mapRect.size.width) * 0.2
mapRect = MKMapRectInset(mapRect, -inset, -inset)
}
if animated {
UIView.animate(withDuration: 0.4) {
self.setVisibleMapRect(mapRect, animated: true)
}
} else {
setVisibleMapRect(mapRect, animated: false)
}
}
/// Removes all annotations from the map.
func removeAllAnnotations() {
removeAnnotations(annotations)
}
/**
Removes overlays of given type from the map.
- parameter type: Type of overlays you want to remove from map.
*/
func removeOverlays<T: MKOverlay>(ofType type: T.Type) {
removeOverlays(overlays.filter { $0.isKind(of: type.self) })
}
/**
Checks if any overlay of given type exists on the map's overlays array.
- parameter type: Type of overlays you want to check exists.
*/
func hasOverlays<T: MKOverlay>(ofType type: T.Type) -> Bool {
return overlays.any { $0.isKind(of: type.self) }
}
/**
Updates region of map using given center coordinate and the radius with animation.
The duration of the animation is 1.0 seconds.
- parameter coordinate: The center point of the new coordinate region.
- parameter radius: The amount of distance in meters from the center.
*/
func setCenter(_ coordinate: CLLocationCoordinate2D, radius: CLLocationDistance) {
UIView.animate(withDuration: 1.0) {
self.setRegion(
MKCoordinateRegionMakeWithDistance(coordinate, radius, radius), animated: true)
}
}
/**
Updates region of map using the current location of the user and the radius.
Internally calls MapView.setCenterCoordinate(withRadius:)
- parameter coordinate: The center point of the new coordinate region.
- parameter radius: The amount of distance in meters from the center.
*/
func setCenterUserLocation(radius: CLLocationDistance) {
setCenter(userCoordinate, radius: radius)
}
}
/// Converts a region to a map rectangle.
func MKMapRectForCoordinateRegion(_ region: MKCoordinateRegion) -> MKMapRect {
let aPoint = MKMapPointForCoordinate(
CLLocationCoordinate2DMake(
region.center.latitude + region.span.latitudeDelta / 2,
region.center.longitude - region.span.longitudeDelta / 2
)
)
let bPoint = MKMapPointForCoordinate(
CLLocationCoordinate2DMake(
region.center.latitude - region.span.latitudeDelta / 2,
region.center.longitude + region.span.longitudeDelta / 2
)
)
return MKMapRectMake(
min(aPoint.x, bPoint.x),
min(aPoint.y, bPoint.y),
abs(aPoint.x - bPoint.x),
abs(aPoint.y - bPoint.y)
)
}
|
gpl-3.0
|
c4d4a288327f987231319588e1b6e40a
| 30.087912 | 98 | 0.692471 | 4.372488 | false | false | false | false |
nixzhu/Proposer
|
Lady/ViewController.swift
|
1
|
4234
|
//
// ViewController.swift
// Lady
//
// Created by NIX on 15/7/11.
// Copyright (c) 2015年 nixWork. All rights reserved.
//
import UIKit
import Proposer
class ViewController: UIViewController {
@IBAction func choosePhoto() {
let photos: PrivateResource = .photos
let propose: Propose = {
proposeToAccess(photos, agreed: {
print("I can access Photos. :]\n")
if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .savedPhotosAlbum
self.present(imagePicker, animated: true, completion: nil)
}
}, rejected: {
self.alertNoPermissionToAccess(photos)
})
}
showProposeMessageIfNeedFor(photos, andTryPropose: propose)
}
@IBAction func takePhoto() {
let camera: PrivateResource = .camera
let propose: Propose = {
proposeToAccess(camera, agreed: {
print("I can access Camera. :]\n")
if UIImagePickerController.isSourceTypeAvailable(.camera){
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .camera
self.present(imagePicker, animated: true, completion: nil)
}
}, rejected: {
self.alertNoPermissionToAccess(camera)
})
}
showProposeMessageIfNeedFor(camera, andTryPropose: propose)
}
@IBAction func recordAudio() {
let microphone: PrivateResource = .microphone
let propose: Propose = {
proposeToAccess(microphone, agreed: {
print("I can access Microphone. :]\n")
}, rejected: {
self.alertNoPermissionToAccess(microphone)
})
}
showProposeMessageIfNeedFor(microphone, andTryPropose: propose)
}
@IBAction func readContacts() {
let contacts: PrivateResource = .contacts
let propose: Propose = {
proposeToAccess(contacts, agreed: {
print("I can access Contacts. :]\n")
}, rejected: {
self.alertNoPermissionToAccess(contacts)
})
}
showProposeMessageIfNeedFor(contacts, andTryPropose: propose)
}
@IBAction func shareLocation() {
let location: PrivateResource = .location(.whenInUse)
let propose: Propose = {
proposeToAccess(location, agreed: {
print("I can access Location. :]\n")
}, rejected: {
self.alertNoPermissionToAccess(location)
})
}
showProposeMessageIfNeedFor(location, andTryPropose: propose)
}
@IBAction func addReminder() {
let reminders: PrivateResource = .reminders
let propose: Propose = {
proposeToAccess(reminders, agreed: {
print("I can access Reminders. :]\n")
}, rejected: {
self.alertNoPermissionToAccess(reminders)
})
}
showProposeMessageIfNeedFor(reminders, andTryPropose: propose)
}
@IBAction func addCalendarEvent() {
let calendar: PrivateResource = .calendar
let propose: Propose = {
proposeToAccess(calendar, agreed: {
print("I can access Calendar. :]\n")
}, rejected: {
self.alertNoPermissionToAccess(calendar)
})
}
showProposeMessageIfNeedFor(calendar, andTryPropose: propose)
}
@IBAction func sendNotifications() {
let settings = UIUserNotificationSettings(
types: [.alert, .badge, .sound],
categories: nil
)
let notifications: PrivateResource = .notifications(settings)
let propose: Propose = {
proposeToAccess(notifications, agreed: {
print("I can send Notifications. :]\n")
}, rejected: {
self.alertNoPermissionToAccess(notifications)
})
}
showProposeMessageIfNeedFor(notifications, andTryPropose: propose)
}
}
|
mit
|
0a0105d0f5b2d040b217fb996d37b0cb
| 33.129032 | 85 | 0.572779 | 4.932401 | false | false | false | false |
blitzagency/ParsedObject
|
Tests/BaseTests.swift
|
1
|
13381
|
// BaseTests.swift
//
// Copyright (c) 2014 Ruoyu Fu, Pinglin Tang
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import ParsedObject
class BaseTests: XCTestCase {
var testData: NSData!
override func setUp() {
super.setUp()
if let file = NSBundle(forClass:BaseTests.self).pathForResource("Tests", ofType: "json") {
self.testData = NSData(contentsOfFile: file)
} else {
XCTFail("Can't find the test JSON file")
}
}
override func tearDown() {
super.tearDown()
}
func testInit() {
let json0 = ParsedObject(data:self.testData)
XCTAssertEqual(json0.array!.count, 3)
XCTAssertEqual(ParsedObject("123").description, "123")
XCTAssertEqual(ParsedObject(["1":"2"])["1"].string!, "2")
var dictionary = NSMutableDictionary()
dictionary.setObject(NSNumber(double: 1.0), forKey: "number" as NSString)
dictionary.setObject(NSNull(), forKey: "null" as NSString)
let json1 = ParsedObject(dictionary)
if let object: AnyObject = NSJSONSerialization.JSONObjectWithData(self.testData, options: nil, error: nil){
let json2 = ParsedObject(object)
XCTAssertEqual(json0, json2)
}
}
func testCompare2() {
let json = ParsedObject("32.1234567890")
}
func testCompare() {
XCTAssertNotEqual(ParsedObject("32.1234567890"), ParsedObject(32.1234567890))
XCTAssertNotEqual(ParsedObject("9876543210987654321"),ParsedObject(NSNumber(unsignedLongLong:9876543210987654321)))
XCTAssertNotEqual(ParsedObject("9876543210987654321.12345678901234567890"), ParsedObject(9876543210987654321.12345678901234567890))
XCTAssertEqual(ParsedObject("😊"), ParsedObject("😊"))
XCTAssertNotEqual(ParsedObject("😱"), ParsedObject("😁"))
XCTAssertEqual(ParsedObject([123,321,456]), ParsedObject([123,321,456]))
XCTAssertNotEqual(ParsedObject([123,321,456]), ParsedObject(123456789))
XCTAssertNotEqual(ParsedObject([123,321,456]), ParsedObject("string"))
XCTAssertNotEqual(ParsedObject(["1":123,"2":321,"3":456]), ParsedObject("string"))
XCTAssertEqual(ParsedObject(["1":123,"2":321,"3":456]), ParsedObject(["2":321,"1":123,"3":456]))
XCTAssertEqual(ParsedObject(NSNull()),ParsedObject(NSNull()))
XCTAssertNotEqual(ParsedObject(NSNull()), ParsedObject(123))
}
func testJSONDoesProduceValidWithCorrectKeyPath() {
let json = ParsedObject(data:self.testData)
let tweets = json
let tweets_array = json.array
let tweets_1 = json[1]
let tweets_array_1 = tweets_1[1]
let tweets_1_user_name = tweets_1["user"]["name"]
let tweets_1_user_name_string = tweets_1["user"]["name"].string
XCTAssertNotEqual(tweets.type, Type.Null)
XCTAssert(tweets_array != nil)
XCTAssertNotEqual(tweets_1.type, Type.Null)
XCTAssertEqual(tweets_1_user_name, ParsedObject("Raffi Krikorian"))
XCTAssertEqual(tweets_1_user_name_string!, "Raffi Krikorian")
let tweets_1_coordinates = tweets_1["coordinates"]
let tweets_1_coordinates_coordinates = tweets_1_coordinates["coordinates"]
let tweets_1_coordinates_coordinates_point_0_double = tweets_1_coordinates_coordinates[0].double
let tweets_1_coordinates_coordinates_point_1_float = tweets_1_coordinates_coordinates[1].float
let new_tweets_1_coordinates_coordinates = ParsedObject([-122.25831,37.871609] as NSArray)
XCTAssertEqual(tweets_1_coordinates_coordinates, new_tweets_1_coordinates_coordinates)
XCTAssertEqual(tweets_1_coordinates_coordinates_point_0_double!, -122.25831)
XCTAssertTrue(tweets_1_coordinates_coordinates_point_1_float! == 37.871609)
let tweets_1_coordinates_coordinates_point_0_string = tweets_1_coordinates_coordinates[0].stringValue
let tweets_1_coordinates_coordinates_point_1_string = tweets_1_coordinates_coordinates[1].stringValue
XCTAssertEqual(tweets_1_coordinates_coordinates_point_0_string, "-122.25831")
XCTAssertEqual(tweets_1_coordinates_coordinates_point_1_string, "37.871609")
let tweets_1_coordinates_coordinates_point_0 = tweets_1_coordinates_coordinates[0]
let tweets_1_coordinates_coordinates_point_1 = tweets_1_coordinates_coordinates[1]
XCTAssertEqual(tweets_1_coordinates_coordinates_point_0, ParsedObject(-122.25831))
XCTAssertEqual(tweets_1_coordinates_coordinates_point_1, ParsedObject(37.871609))
let created_at = json[0]["created_at"].string
let id_str = json[0]["id_str"].string
let favorited = json[0]["favorited"].bool
let id = json[0]["id"].int
let in_reply_to_user_id_str = json[0]["in_reply_to_user_id_str"]
XCTAssertEqual(created_at!, "Tue Aug 28 21:16:23 +0000 2012")
XCTAssertEqual(id_str!,"240558470661799936")
XCTAssertFalse(favorited!)
XCTAssertEqual(id!,240558470661799936)
XCTAssertEqual(in_reply_to_user_id_str.type, Type.Null)
let user = json[0]["user"]
let user_name = user["name"].string
let user_profile_image_url = user["profile_image_url"].URL
XCTAssert(user_name == "OAuth Dancer")
XCTAssert(user_profile_image_url == NSURL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg"))
let user_dictionary = json[0]["user"].dictionary
let user_dictionary_name = user_dictionary?["name"]?.string
let user_dictionary_name_profile_image_url = user_dictionary?["profile_image_url"]?.URL
XCTAssert(user_dictionary_name == "OAuth Dancer")
XCTAssert(user_dictionary_name_profile_image_url == NSURL(string: "http://a0.twimg.com/profile_images/730275945/oauth-dancer_normal.jpg"))
}
func testSequenceType() {
let json = ParsedObject(data:self.testData)
XCTAssertEqual(json.count, 3)
for (_, aJson) in json {
XCTAssertEqual(aJson, json[0])
break
}
var index = 0
let keys = (json[1].dictionaryObject! as NSDictionary).allKeys as [String]
for (aKey, aJson) in json[1] {
XCTAssertEqual(aKey, keys[index])
XCTAssertEqual(aJson, json[1][keys[index]])
break
}
}
func testJSONNumberCompare() {
XCTAssertEqual(ParsedObject(12376352.123321), ParsedObject(12376352.123321))
XCTAssertGreaterThan(ParsedObject(20.211), ParsedObject(20.112))
XCTAssertGreaterThanOrEqual(ParsedObject(30.211), ParsedObject(20.112))
XCTAssertGreaterThanOrEqual(ParsedObject(65232), ParsedObject(65232))
XCTAssertLessThan(ParsedObject(-82320.211), ParsedObject(20.112))
XCTAssertLessThanOrEqual(ParsedObject(-320.211), ParsedObject(123.1))
XCTAssertLessThanOrEqual(ParsedObject(-8763), ParsedObject(-8763))
XCTAssertEqual(ParsedObject(12376352.123321), ParsedObject(12376352.123321))
XCTAssertGreaterThan(ParsedObject(20.211), ParsedObject(20.112))
XCTAssertGreaterThanOrEqual(ParsedObject(30.211), ParsedObject(20.112))
XCTAssertGreaterThanOrEqual(ParsedObject(65232), ParsedObject(65232))
XCTAssertLessThan(ParsedObject(-82320.211), ParsedObject(20.112))
XCTAssertLessThanOrEqual(ParsedObject(-320.211), ParsedObject(123.1))
XCTAssertLessThanOrEqual(ParsedObject(-8763), ParsedObject(-8763))
}
func testNumberConverToString(){
XCTAssertEqual(ParsedObject(true).stringValue, "true")
XCTAssertEqual(ParsedObject(999.9823).stringValue, "999.9823")
XCTAssertEqual(ParsedObject(true).number!.stringValue, "1")
XCTAssertEqual(ParsedObject(false).number!.stringValue, "0")
XCTAssertEqual(ParsedObject("hello").numberValue.stringValue, "0")
XCTAssertEqual(ParsedObject(NSNull()).numberValue.stringValue, "0")
XCTAssertEqual(ParsedObject(["a","b","c","d"]).numberValue.stringValue, "0")
XCTAssertEqual(ParsedObject(["a":"b","c":"d"]).numberValue.stringValue, "0")
}
func testNumberPrint(){
XCTAssertEqual(ParsedObject(false).description,"false")
XCTAssertEqual(ParsedObject(true).description,"true")
XCTAssertEqual(ParsedObject(1).description,"1")
XCTAssertEqual(ParsedObject(22).description,"22")
#if (arch(x86_64) || arch(arm64))
XCTAssertEqual(ParsedObject(9.22337203685478E18).description,"9.22337203685478e+18")
#elseif (arch(i386) || arch(arm))
XCTAssertEqual(ParsedObject(2147483647).description,"2147483647")
#endif
XCTAssertEqual(ParsedObject(-1).description,"-1")
XCTAssertEqual(ParsedObject(-934834834).description,"-934834834")
XCTAssertEqual(ParsedObject(-2147483648).description,"-2147483648")
XCTAssertEqual(ParsedObject(1.5555).description,"1.5555")
XCTAssertEqual(ParsedObject(-9.123456789).description,"-9.123456789")
XCTAssertEqual(ParsedObject(-0.00000000000000001).description,"-1e-17")
XCTAssertEqual(ParsedObject(-999999999999999999999999.000000000000000000000001).description,"-1e+24")
XCTAssertEqual(ParsedObject(-9999999991999999999999999.88888883433343439438493483483943948341).stringValue,"-9.999999991999999e+24")
XCTAssertEqual(ParsedObject(Int(Int.max)).description,"\(Int.max)")
XCTAssertEqual(ParsedObject(NSNumber(long: Int.min)).description,"\(Int.min)")
XCTAssertEqual(ParsedObject(NSNumber(unsignedLong: ULONG_MAX)).description,"\(ULONG_MAX)")
XCTAssertEqual(ParsedObject(NSNumber(unsignedLongLong: UInt64.max)).description,"\(UInt64.max)")
XCTAssertEqual(ParsedObject(NSNumber(longLong: Int64.max)).description,"\(Int64.max)")
XCTAssertEqual(ParsedObject(NSNumber(unsignedLongLong: UInt64.max)).description,"\(UInt64.max)")
XCTAssertEqual(ParsedObject(Double.infinity).description,"inf")
XCTAssertEqual(ParsedObject(-Double.infinity).description,"-inf")
XCTAssertEqual(ParsedObject(Double.NaN).description,"nan")
XCTAssertEqual(ParsedObject(1.0/0.0).description,"inf")
XCTAssertEqual(ParsedObject(-1.0/0.0).description,"-inf")
XCTAssertEqual(ParsedObject(0.0/0.0).description,"nan")
}
func testNullParsedObject() {
XCTAssertEqual(ParsedObject(NSNull()).debugDescription,"null")
let json:ParsedObject = nil
XCTAssertEqual(json.debugDescription,"null")
XCTAssertNil(json.error)
let json1:ParsedObject = ParsedObject(NSNull())
if json1 != nil {
XCTFail("json1 should be nil")
}
}
func testErrorHandle() {
let json = ParsedObject(data:self.testData)
if let wrongType = json["wrong-type"].string {
XCTFail("Should not run into here")
} else {
XCTAssertEqual(json["wrong-type"].error!.code, ErrorWrongType)
}
if let notExist = json[0]["not-exist"].string {
XCTFail("Should not run into here")
} else {
XCTAssertEqual(json[0]["not-exist"].error!.code, ErrorNotExist)
}
let wrongJSON = ParsedObject(NSObject())
if let error = wrongJSON.error {
XCTAssertEqual(error.code, ErrorUnsupportedType)
}
}
func testReturnObject() {
let json = ParsedObject(data:self.testData)
XCTAssertNotNil(json.object)
}
func testNumberCompare(){
XCTAssertEqual(NSNumber(double: 888332), NSNumber(int:888332))
XCTAssertNotEqual(NSNumber(double: 888332.1), NSNumber(int:888332))
XCTAssertLessThan(NSNumber(int: 888332), NSNumber(double:888332.1))
XCTAssertGreaterThan(NSNumber(double: 888332.1), NSNumber(int:888332))
XCTAssertNotEqual(NSNumber(double: 1), NSNumber(bool:true))
XCTAssertNotEqual(NSNumber(int: 0), NSNumber(bool:false))
XCTAssertEqual(NSNumber(bool: false), NSNumber(bool:false))
XCTAssertEqual(NSNumber(bool: true), NSNumber(bool:true))
}
}
|
mit
|
9f69be9982ff167b1afa6f5b4e412060
| 48.88806 | 146 | 0.676191 | 4.283563 | false | true | false | false |
JohnEstropia/CoreStore
|
Sources/NSEntityDescription+DynamicModel.swift
|
1
|
6021
|
//
// NSEntityDescription+DynamicModel.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import CoreData
import Foundation
// MARK: - NSEntityDescription
extension NSEntityDescription {
@nonobjc
internal var dynamicObjectType: DynamicObject.Type? {
guard let userInfo = self.userInfo,
let typeName = userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] as! String? else {
return nil
}
return (NSClassFromString(typeName) as! DynamicObject.Type)
}
@nonobjc
internal var coreStoreEntity: DynamicEntity? {
get {
guard let userInfo = self.userInfo,
let typeName = userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] as! String?,
let entityName = userInfo[UserInfoKey.CoreStoreManagedObjectEntityName] as! String?,
let isAbstract = userInfo[UserInfoKey.CoreStoreManagedObjectIsAbstract] as! Bool?,
let indexes = userInfo[UserInfoKey.CoreStoreManagedObjectIndexes] as! [[KeyPathString]]?,
let uniqueConstraints = userInfo[UserInfoKey.CoreStoreManagedObjectUniqueConstraints] as! [[KeyPathString]]? else {
return nil
}
return DynamicEntity(
type: NSClassFromString(typeName) as! CoreStoreObject.Type,
entityName: entityName,
isAbstract: isAbstract,
versionHashModifier: userInfo[UserInfoKey.CoreStoreManagedObjectVersionHashModifier] as! String?,
indexes: indexes,
uniqueConstraints: uniqueConstraints
)
}
set {
if let newValue = newValue {
cs_setUserInfo { (userInfo) in
userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] = NSStringFromClass(newValue.type)
userInfo[UserInfoKey.CoreStoreManagedObjectEntityName] = newValue.entityName
userInfo[UserInfoKey.CoreStoreManagedObjectIsAbstract] = newValue.isAbstract
userInfo[UserInfoKey.CoreStoreManagedObjectVersionHashModifier] = newValue.versionHashModifier
userInfo[UserInfoKey.CoreStoreManagedObjectIndexes] = newValue.indexes
userInfo[UserInfoKey.CoreStoreManagedObjectUniqueConstraints] = newValue.uniqueConstraints
}
}
else {
cs_setUserInfo { (userInfo) in
userInfo[UserInfoKey.CoreStoreManagedObjectTypeName] = nil
userInfo[UserInfoKey.CoreStoreManagedObjectEntityName] = nil
userInfo[UserInfoKey.CoreStoreManagedObjectIsAbstract] = nil
userInfo[UserInfoKey.CoreStoreManagedObjectVersionHashModifier] = nil
userInfo[UserInfoKey.CoreStoreManagedObjectIndexes] = nil
userInfo[UserInfoKey.CoreStoreManagedObjectUniqueConstraints] = nil
}
}
}
}
@nonobjc
internal var keyPathsByAffectedKeyPaths: [KeyPathString: Set<KeyPathString>] {
get {
if let userInfo = self.userInfo,
let value = userInfo[UserInfoKey.CoreStoreManagedObjectKeyPathsByAffectedKeyPaths] {
return value as! [KeyPathString: Set<KeyPathString>]
}
return [:]
}
set {
cs_setUserInfo { (userInfo) in
userInfo[UserInfoKey.CoreStoreManagedObjectKeyPathsByAffectedKeyPaths] = newValue
}
}
}
// MARK: Private
// MARK: - UserInfoKey
private enum UserInfoKey {
fileprivate static let CoreStoreManagedObjectTypeName = "CoreStoreManagedObjectTypeName"
fileprivate static let CoreStoreManagedObjectEntityName = "CoreStoreManagedObjectEntityName"
fileprivate static let CoreStoreManagedObjectIsAbstract = "CoreStoreManagedObjectIsAbstract"
fileprivate static let CoreStoreManagedObjectVersionHashModifier = "CoreStoreManagedObjectVersionHashModifier"
fileprivate static let CoreStoreManagedObjectIndexes = "CoreStoreManagedObjectIndexes"
fileprivate static let CoreStoreManagedObjectUniqueConstraints = "CoreStoreManagedObjectUniqueConstraints"
fileprivate static let CoreStoreManagedObjectKeyPathsByAffectedKeyPaths = "CoreStoreManagedObjectKeyPathsByAffectedKeyPaths"
}
private func cs_setUserInfo(_ closure: (_ userInfo: inout [AnyHashable: Any]) -> Void) {
var userInfo = self.userInfo ?? [:]
closure(&userInfo)
self.userInfo = userInfo
}
}
|
mit
|
614c1546e08923029a5a4615148d9ea5
| 41.394366 | 132 | 0.647342 | 6.026026 | false | false | false | false |
SheffieldKevin/SwiftGraphics
|
Playgrounds/Points.playground/Contents.swift
|
1
|
3748
|
//: Playground - noun: a place where people can play
// Order of imports is very important
import CoreGraphics
import SwiftUtilities
import SwiftRandom
import SwiftGraphics
import SwiftGraphicsPlayground
public extension NSGraphicsContext {
static func with(context: CGContextRef, flipped: Bool, block: Void -> Void) {
let savedContext = NSGraphicsContext.currentContext()
let newContext = NSGraphicsContext(CGContext: context, flipped: flipped)
NSGraphicsContext.setCurrentContext(newContext)
block()
NSGraphicsContext.setCurrentContext(savedContext)
}
}
public extension CGContext {
func drawLabel(string: String, point: CGPoint, size: CGFloat) {
NSGraphicsContext.with(self, flipped: false) {
let attributes = [NSFontAttributeName: NSFont.labelFontOfSize(size)]
let nsString = (string as NSString)
nsString.drawAtPoint(point, withAttributes: attributes)
}
}
}
let context = CGContextRef.bitmapContext(CGSize(w: 480, h: 320), origin: CGPoint(x: 0.0, y: 0.0))
context.style
let rng = SwiftUtilities.random
var points = random.arrayOfRandomPoints(50, range: CGRect(w: 480, h: 320).insetBy(dx: 50, dy: 50))
points.count
context.strokeColor = NSColor.blueColor().colorWithAlphaComponent(0.2).CGColor
for (index, point) in points.enumerate() {
context.strokeCross(CGRect(center: point, radius: 5))
}
context.strokeColor = CGColor.blueColor()
let hull = monotoneChain(points, sorted: false)
context.strokeLine(hull, closed: true)
context.strokeColor = CGColor.blackColor()
for (index, point) in hull.enumerate() {
context.drawLabel("\(index)", point: point, size: 9)
}
/**
Tests if a point is Left|On|Right of an infinite line.
- parameter line: Two points on an infinite line
- parameter point: Point to test
- returns: > 0 if point on left of the line
= 0 if point on the line
< 0 if point on right of the line
*/
func turn(line line: (CGPoint, CGPoint), point: CGPoint) -> CGFloat {
return (line.1.x - line.0.x) * (point.y - line.0.y) - (point.x - line.0.x) * (line.1.y - line.0.y)
}
//====================
/**
From: http://geomalgorithms.com/a03-_inclusion.html
- parameter point: Vertices on a closed, clockwise winding polygon
- parameter polygon: Array of points
- returns: True if point inside points of polygon
*/
func pointInPolygon(point: CGPoint, polygon: [CGPoint]) -> Bool {
// The winding number counter
var wn = 0
// Loop through all edges of the polygon
// edge from V[i] to V[i+1]
for var i=0; i != polygon.count - 1; i++ {
// start y <= P.y
if polygon[i].y <= point.y {
// an upward crossing
if polygon[i+1].y > point.y {
// P left of edge
if turn(line: (polygon[i], polygon[i+1]), point: point) > 0 {
// have a valid up intersect
++wn
}
}
}
else {
// start y > P.y (no test needed)
// a downward crossing
if polygon[i+1].y <= point.y {
// P right of edge
if turn(line: (polygon[i], polygon[i+1]), point: point) < 0 {
// have a valid down intersect
wn -= 1
}
}
}
}
return wn != 0
}
let reversed = Array(hull.reverse())
let closed = reversed + [reversed[0]]
for N in 0..<100 {
let point = random.random(range: CGRect(w: 480, h: 320))
context.strokeColor = pointInPolygon(point, polygon: closed) ? CGColor.greenColor() : CGColor.redColor()
context.strokeCross(CGRect(center: point, radius: 5))
}
context.nsimage
|
bsd-2-clause
|
132c450f1d365816bece3362c30d0f86
| 29.975207 | 108 | 0.621665 | 3.932844 | false | false | false | false |
cherrywoods/swift-meta-serialization
|
Examples/Example1/Example1.swift
|
1
|
2241
|
//
// Example1.swift
// MetaSerializationTests macOS
//
// Available at the terms of the LICENSE file included in this project.
// If none is included, available at the terms of the unlicense, see www.unlicense.org
//
import Foundation
@testable import MetaSerialization
enum Example1 {
static let translator = PrimitivesEnumTranslator(primitives: [ .nil, .bool, .string, .int, .double ])
static let serialization = SimpleSerialization<Example1Container>(translator: Example1.translator,
encodeFromMeta: encodeToContainer,
decodeToMeta: decodeFromContainer)
}
func encodeToContainer(_ input: Meta) -> Example1Container {
// input is eigther NilMarker, Bool, String, Int or Double
if input is NilMarker {
return Example1Container.nil
} else if let bool = input as? Bool {
return Example1Container.bool(bool)
} else if let string = input as? String {
return Example1Container.string(string)
} else if let int = input as? Int {
return Example1Container.int(int)
} else if let double = input as? Double {
return Example1Container.double(double)
} else if let metaArray = input as? [Meta] {
return Example1Container.array( metaArray.map(encodeToContainer) )
} else if let metaDictionary = input as? [String : Meta] {
return Example1Container.dictionary( metaDictionary.mapValues(encodeToContainer) )
}
// execution of this shows a bug
preconditionFailure()
}
func decodeFromContainer(_ container: Example1Container) -> Meta {
switch container {
case .nil:
return NilMarker.instance
case .bool(let value):
return value
case .string(let value):
return value
case .int(let value):
return value
case .double(let value):
return value
case .array(let array):
return array.map(decodeFromContainer)
case .dictionary(let dictionary):
return dictionary.mapValues(decodeFromContainer)
}
}
|
apache-2.0
|
e936e342e39312121d541433b3474006
| 28.486842 | 105 | 0.617581 | 4.707983 | false | false | false | false |
Dev1an/Bond
|
Bond/iOS/Bond+UITextField.swift
|
2
|
4795
|
//
// Bond+UITextField.swift
// Bond
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
class TextFieldDynamicHelper
{
weak var control: UITextField?
var listener: (String -> Void)?
init(control: UITextField) {
self.control = control
control.addTarget(self, action: Selector("editingChanged:"), forControlEvents: .EditingChanged)
}
func editingChanged(control: UITextField) {
self.listener?(control.text ?? "")
}
deinit {
control?.removeTarget(self, action: nil, forControlEvents: .EditingChanged)
}
}
class TextFieldDynamic<T>: InternalDynamic<String>
{
let helper: TextFieldDynamicHelper
init(control: UITextField) {
self.helper = TextFieldDynamicHelper(control: control)
super.init(control.text ?? "")
self.helper.listener = { [unowned self] in
self.updatingFromSelf = true
self.value = $0
self.updatingFromSelf = false
}
}
}
private var textDynamicHandleUITextField: UInt8 = 0;
private var enabledDynamicHandleUITextField: UInt8 = 0;
extension UITextField /*: Dynamical, Bondable */ {
public var dynText: Dynamic<String> {
if let d: AnyObject = objc_getAssociatedObject(self, &textDynamicHandleUITextField) {
return (d as? Dynamic<String>)!
} else {
let d = TextFieldDynamic<String>(control: self)
let bond = Bond<String>() { [weak self, weak d] v in
if let s = self, d = d where !d.updatingFromSelf {
s.text = v
}
}
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &textDynamicHandleUITextField, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var dynEnabled: Dynamic<Bool> {
if let d: AnyObject = objc_getAssociatedObject(self, &enabledDynamicHandleUITextField) {
return (d as? Dynamic<Bool>)!
} else {
let d = InternalDynamic<Bool>(self.enabled)
let bond = Bond<Bool>() { [weak self] v in if let s = self { s.enabled = v } }
d.bindTo(bond, fire: false, strongly: false)
d.retain(bond)
objc_setAssociatedObject(self, &enabledDynamicHandleUITextField, d, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return d
}
}
public var designatedDynamic: Dynamic<String> {
return self.dynText
}
public var designatedBond: Bond<String> {
return self.dynText.valueBond
}
}
public func ->> (left: UITextField, right: Bond<String>) {
left.designatedDynamic ->> right
}
public func ->> <U: Bondable where U.BondType == String>(left: UITextField, right: U) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UITextField) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UILabel) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: UITextField, right: UITextView) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> <T: Dynamical where T.DynamicType == String>(left: T, right: UITextField) {
left.designatedDynamic ->> right.designatedBond
}
public func ->> (left: Dynamic<String>, right: UITextField) {
left ->> right.designatedBond
}
public func <->> (left: UITextField, right: UITextField) {
left.designatedDynamic <->> right.designatedDynamic
}
public func <->> (left: Dynamic<String>, right: UITextField) {
left <->> right.designatedDynamic
}
public func <->> (left: UITextField, right: Dynamic<String>) {
left.designatedDynamic <->> right
}
public func <->> (left: UITextField, right: UITextView) {
left.designatedDynamic <->> right.designatedDynamic
}
|
mit
|
a36326c568d1572cf705327d5d4b8816
| 30.966667 | 131 | 0.701356 | 4.169565 | false | false | false | false |
muukii/RequestKit
|
RequestKit/Source/Dispatcher.swift
|
2
|
19346
|
//
// Request.swift
// couples
//
// Created by Muukii on 10/26/14.
// Copyright (c) 2014 eureka. All rights reserved.
//
import Foundation
import AFNetworking
let sessionIdentifier = "me.muukii.requestKit.background_session"
public class Dispatcher: NSObject {
private func RKLog<T>(value: T) {
#if DEBUG
println(value)
#else
#endif
}
public enum NetworkStatus: Int {
case Unknown = -1
case NotReachable = 0
case ViaWWAN = 1
case ViaWiFi = 2
}
var defaultSessionManager: AFHTTPSessionManager?
var backgroundSessionManager: AFHTTPSessionManager?
var reachabilityManager: AFNetworkReachabilityManager?
public private(set) var networkStatus: NetworkStatus = .Unknown
public private(set) var runningRequests: NSMutableSet = NSMutableSet()
var backgroundURLSessionCompletion: (() -> ())?
public override init() {
super.init()
var backgroundTask = UIBackgroundTaskInvalid
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithName("me.muukii.requestKit.background_task", expirationHandler: { () -> Void in
UIApplication.sharedApplication().endBackgroundTask(backgroundTask)
backgroundTask = UIBackgroundTaskInvalid
})
self.reachabilityManager = AFNetworkReachabilityManager.sharedManager()
self.reachabilityManager?.startMonitoring()
self.reachabilityManager?.setReachabilityStatusChangeBlock({ (status: AFNetworkReachabilityStatus) -> Void in
self.networkStatus = NetworkStatus(rawValue: status.rawValue) ?? .Unknown
self.changedReachabilityStatus(NetworkStatus(rawValue: status.rawValue) ?? .Unknown)
})
let defaultSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
self.defaultSessionManager = AFHTTPSessionManager(sessionConfiguration: defaultSessionConfiguration)
self.defaultSessionManager?.requestSerializer = AFHTTPRequestSerializer()
var backgroundSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(sessionIdentifier)
self.backgroundSessionManager = AFHTTPSessionManager(sessionConfiguration: backgroundSessionConfiguration)
self.backgroundSessionManager?.setDownloadTaskDidFinishDownloadingBlock({ (session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, url: NSURL!) -> NSURL! in
return url
})
self.backgroundSessionManager?.setDidFinishEventsForBackgroundURLSessionBlock({ [unowned self] (session: NSURLSession!) -> Void in
session.configuration.identifier
if let completion = self.backgroundURLSessionCompletion {
completion()
self.backgroundURLSessionCompletion = nil
}
})
self.backgroundSessionManager?.setTaskDidReceiveAuthenticationChallengeBlock({ (session: NSURLSession!, task: NSURLSessionTask!, challenge: NSURLAuthenticationChallenge!, credential: AutoreleasingUnsafeMutablePointer<NSURLCredential?>) -> NSURLSessionAuthChallengeDisposition in
return .PerformDefaultHandling
})
}
deinit {
self.reachabilityManager?.stopMonitoring()
}
func handleEventsForBackgroundURLSession(identifier: String!, completionHandler: () -> ()) {
assert(identifier == sessionIdentifier, "Unknown session identifier.")
self.backgroundURLSessionCompletion = completionHandler
}
public func changedReachabilityStatus(status: NetworkStatus) {
switch status {
case .Unknown:
RKLog("Network status changed: Unknown")
case .NotReachable:
RKLog("Network status changed: Not Reachable")
case .ViaWWAN:
RKLog("Network status changed: WWAN")
fallthrough
case .ViaWiFi:
RKLog("Network status changed: WiFi")
self.retryRequests()
}
}
/**
Connection: Success
:param: urlResponse
:param: object
:param: error
:param: request
*/
public func centralProcessSuccess<T: Request>(
urlResponse: NSHTTPURLResponse?,
object: NSObject?,
error: NSError?,
request: T) {
self.runningRequests.removeObject(request)
request.updateStatus(.Success)
}
/**
Connection: Failure
:param: urlResponse
:param: object
:param: error
:param: request
*/
public func centralProcessFailure<T: Request>(
urlResponse: NSHTTPURLResponse?,
object: NSObject?,
error: NSError?,
request: T) {
self.runningRequests.removeObject(request)
request.updateStatus(.Failure)
#if DEBUG
if let urlResponse = urlResponse {
JELogAlert("Response code \(urlResponse.statusCode) from \"\(urlResponse.URL!.absoluteString!)\"")
}
#endif
if let error = error where request.autoRetryConfiguration.failOnErrorHandler?(error) == true {
request.failureHandler?(urlResponse: urlResponse, responseObject: object, error: error)
return
}
if request.retryCount > request.autoRetryConfiguration.maxRetryCount
|| (error != nil && error!.domain == NSURLErrorDomain && error!.code == NSURLErrorCancelled) {
request.failureHandler?(urlResponse: urlResponse, responseObject: object, error: error)
return
}
if UIApplication.sharedApplication().applicationState == UIApplicationState.Background &&
request.autoRetryConfiguration.enableBackgroundRetry == false {
request.failureHandler?(urlResponse: urlResponse, responseObject: object, error: error)
return
}
let delay = request.autoRetryConfiguration.breakTime
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) { () -> Void in
self.retryRequest(request)
}
}
/**
Connection: Completion
:param: urlResponse
:param: object
:param: error
:param: request
*/
public func centralProcessCompletion<T: Request>(#request: T) {
request.completionHandler?()
}
public func invalidateAllRunningRequests() {
for request in self.runningRequests {
let request: Request = request as! Request
request.updateRetryCount(request.autoRetryConfiguration.maxRetryCount)
request.updateStatus(.Failure)
// TODO : NSError for invalidate.
request.failureHandler?(urlResponse: nil, responseObject: nil, error: nil)
}
self.runningRequests.removeAllObjects()
}
/**
Dispatch Request
:param: request
*/
public func dispatch<T: Request>(request: T) {
if request.autoRetryConfiguration.failWhenNotReachable == true && self.networkStatus == .NotReachable {
// NotReachableのNSErrorを作る
request.failureHandler?(urlResponse: nil, responseObject: nil, error: nil)
self.centralProcessCompletion(request: request)
return
}
self.runningRequests.addObject((request))
request.updateStatus(.Running)
if let component = request.component {
request.component?.parameters = request.appendDefaultParameters(component.parameters)
let sessionManager: AFHTTPSessionManager?
switch request.sessionType {
case .Default:
sessionManager = self.defaultSessionManager
case .Background:
let application = UIApplication.sharedApplication()
var taskID = UIBackgroundTaskInvalid
taskID = application.beginBackgroundTaskWithExpirationHandler {
application.endBackgroundTask(taskID)
taskID = UIBackgroundTaskInvalid
}
sessionManager = self.backgroundSessionManager
}
if let sessionManager = sessionManager {
switch component.taskType {
case .Data:
self.dispatchForDataTask(request: request, sessionManager: sessionManager)
case .Upload(let data):
self.dispatchForUploadTask(request: request, uploadData: data, sessionManager: sessionManager)
}
}
} else {
request.updateStatus(.Failure)
assert(false, "Component is nil")
}
}
private func absoluteUrlString(request: Request) -> String {
let baseUrlString = request.baseURL?.absoluteString
let urlString = baseUrlString?.stringByAppendingPathComponent(request.component?.path ?? "")
return urlString ?? ""
}
public func dispathForDownloadTask(
#fileName: String,
downloadUrl: NSURL,
downloadDestination: NSURL,
progress: ((progress: Float) -> Void)?,
success: ((fileUrl: NSURL, response: NSHTTPURLResponse?) -> Void)?,
failure: ((error: NSError?) -> Void)?) {
var error: NSError?
let urlRequest = AFHTTPRequestSerializer().requestWithMethod (
"GET",
URLString: downloadUrl.absoluteString,
parameters: nil,
error: &error)
var task: NSURLSessionTask?
task = self.defaultSessionManager?.downloadTaskWithRequest(urlRequest, progress: nil, destination: { (url, response) -> NSURL! in
return downloadDestination.URLByAppendingPathComponent(fileName)
}, completionHandler: { (response, url, error) -> Void in
if let task = task {
self.downloadTaskProgressDictionary.removeValueForKey("\(task.taskIdentifier)")
}
if error == nil {
success?(fileUrl: url, response: response as! NSHTTPURLResponse?)
} else {
failure?(error:error)
}
})
if let progress = progress {
if let task = task {
self.downloadTaskProgressDictionary["\(task.taskIdentifier)"] = progress
}
}
self.defaultSessionManager?.setDownloadTaskDidWriteDataBlock({ (session: NSURLSession?, task: NSURLSessionTask!, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) -> Void in
if let progress = self.dataTaskProgressDictionary["\(task.taskIdentifier)"] {
progress(progress: Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
}
})
if let task = task {
task.resume()
}
}
public func retryRequest<T: Request>(request: T) {
if self.networkStatus == .NotReachable {
request.updateStatus(.PendingRetry)
self.runningRequests.addObject(request)
return
}
request.updateRetryCount(request.retryCount + 1)
self.dispatch(request)
}
public func retryRequests() {
for request in self.runningRequests {
let request = request as! Request
if request.status == .PendingRetry {
self.retryRequest(request)
}
}
}
// MARK: Private
private var downloadTaskProgressDictionary = [String : Progress]()
/**
Dispatch For DataTask
:param: request
:param: sessionManager
*/
typealias Progress = Request.Progress
private var dataTaskProgressDictionary = [String : Progress]()
private func dispatchForDataTask(#request: Request, sessionManager: AFHTTPSessionManager) {
if let component = request.component {
var error: NSError? = nil
let urlRequest = AFHTTPRequestSerializer().requestWithMethod (
component.method.rawValue,
URLString: self.absoluteUrlString(request) as String,
parameters: component.validatedParameters,
error: &error)
urlRequest.timeoutInterval = 20
var task: NSURLSessionTask?
task = sessionManager.dataTaskWithRequest(urlRequest, completionHandler: { (urlResponse: NSURLResponse?, object: AnyObject?, error: NSError?) -> Void in
if error == nil {
var error: NSError? = nil
if let object = (object as? NSObject) {
self.centralProcessSuccess((urlResponse as! NSHTTPURLResponse?), object: object , error: error, request: request)
} else {
self.centralProcessFailure((urlResponse as! NSHTTPURLResponse?), object: nil , error: error, request: request)
}
} else {
self.centralProcessFailure((urlResponse as! NSHTTPURLResponse?), object: nil, error: error, request: request)
}
if let task = task {
self.dataTaskProgressDictionary.removeValueForKey("\(task.taskIdentifier)")
}
self.centralProcessCompletion(request: request)
})
if let progress = request.progressHandler, task = task {
self.dataTaskProgressDictionary["\(task.taskIdentifier)"] = progress
}
sessionManager.setTaskDidSendBodyDataBlock({ (session: NSURLSession?, task: NSURLSessionTask!, sendBytes, totalSendBytes, totalBytesExpectedToSend) -> Void in
if let progress = self.dataTaskProgressDictionary["\(task.taskIdentifier)"] {
progress(progress: Float(totalSendBytes) / Float(totalBytesExpectedToSend))
}
})
request.setSessionTask(task)
task?.resume()
} else {
assert(false, "Request: Component is nil")
}
}
/**
Dispatch For Upload Task (Foreground Only)
:param: request
:param: sessionManager
*/
private var uploadTaskProgressDictionary = [String : Progress]()
private func dispatchForUploadTask(#request: Request, uploadData: [Request.UploadData], sessionManager: AFHTTPSessionManager) {
if let component = request.component {
var bodyConstructionBlock: ((formData: AFMultipartFormData!) -> Void)?
bodyConstructionBlock = { (formData) -> Void in
for data in uploadData {
switch data {
case .Data(let data, let name, let fileName):
formData.appendPartWithFileData(
data,
name: name,
fileName: fileName,
mimeType: NSURL(fileURLWithPath: fileName)!.mimeType())
case .Stream(let stream, let name, let fileName, let length):
formData.appendPartWithInputStream(
stream,
name: name,
fileName: fileName,
length: length,
mimeType: NSURL(fileURLWithPath: fileName)!.mimeType())
case .URL(let fileUrl, let name):
formData.appendPartWithFileURL(
fileUrl,
name: name,
fileName: fileUrl.lastPathComponent,
mimeType: fileUrl.mimeType(),
error: nil)
}
}
}
let urlRequest = AFHTTPRequestSerializer().multipartFormRequestWithMethod(
component.method.rawValue,
URLString: self.absoluteUrlString(request) as String,
parameters: component.validatedParameters,
constructingBodyWithBlock: bodyConstructionBlock,
error: nil)
var task: NSURLSessionTask?
task = sessionManager.uploadTaskWithStreamedRequest(urlRequest, progress: nil, completionHandler: { (urlResponse, object, error) -> Void in
if error == nil {
var error: NSError? = nil
if let object = (object as? NSObject) {
self.centralProcessSuccess((urlResponse as! NSHTTPURLResponse?), object: object as NSObject , error: error, request: request)
} else {
self.centralProcessFailure((urlResponse as! NSHTTPURLResponse?), object: nil , error: error, request: request)
}
} else {
self.centralProcessFailure((urlResponse as! NSHTTPURLResponse?), object: nil, error: error, request: request)
}
if let task = task {
self.uploadTaskProgressDictionary.removeValueForKey("\(task.taskIdentifier)")
}
self.centralProcessCompletion(request: request)
})
request.setSessionTask(task)
if let progress = request.progressHandler, task = task {
self.uploadTaskProgressDictionary["\(task.taskIdentifier)"] = progress
}
sessionManager.setTaskDidSendBodyDataBlock({ (session: NSURLSession?, task: NSURLSessionTask!, sendBytes, totalSendBytes, totalBytesExpectedToSend) -> Void in
if let progress = self.uploadTaskProgressDictionary["\(task.taskIdentifier)"] {
progress(progress: Float(totalSendBytes) / Float(totalBytesExpectedToSend))
}
})
task?.resume()
}
}
}
private extension NSURL {
func UTI() -> String {
let stringRef: Unmanaged<CFString> = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, self.pathExtension, nil)
let string = stringRef.takeUnretainedValue()
return string as! String
}
func mimeType() -> String {
let stringRef: Unmanaged<CFString> = UTTypeCopyPreferredTagWithClass(self.UTI(), kUTTagClassMIMEType)
let string = stringRef.takeUnretainedValue()
return string as! String
}
}
|
mit
|
bc0d01cce3743e0807b3a4d3d8c075d2
| 37.676 | 286 | 0.581084 | 6.208026 | false | false | false | false |
KeithPiTsui/Pavers
|
Pavers/Sources/UI/ReactiveCocoa/NSObject+Association.swift
|
1
|
4156
|
import PaversFRP
internal struct AssociationKey<Value> {
fileprivate let address: UnsafeRawPointer
fileprivate let `default`: Value!
/// Create an ObjC association key.
///
/// - warning: The key must be uniqued.
///
/// - parameters:
/// - default: The default value, or `nil` to trap on undefined value. It is
/// ignored if `Value` is an optional.
init(default: Value? = nil) {
self.address = UnsafeRawPointer(UnsafeMutablePointer<UInt8>.allocate(capacity: 1))
self.default = `default`
}
/// Create an ObjC association key from a `StaticString`.
///
/// - precondition: `key` has a pointer representation.
///
/// - parameters:
/// - default: The default value, or `nil` to trap on undefined value. It is
/// ignored if `Value` is an optional.
init(_ key: StaticString, default: Value? = nil) {
assert(key.hasPointerRepresentation)
self.address = UnsafeRawPointer(key.utf8Start)
self.default = `default`
}
/// Create an ObjC association key from a `Selector`.
///
/// - parameters:
/// - default: The default value, or `nil` to trap on undefined value. It is
/// ignored if `Value` is an optional.
init(_ key: Selector, default: Value? = nil) {
self.address = UnsafeRawPointer(key.utf8Start)
self.default = `default`
}
}
internal struct Associations<Base: AnyObject> {
fileprivate let base: Base
init(_ base: Base) {
self.base = base
}
}
extension Reactive where Base: NSObjectProtocol {
/// Retrieve the associated value for the specified key. If the value does not
/// exist, `initial` would be called and the returned value would be
/// associated subsequently.
///
/// - parameters:
/// - key: An optional key to differentiate different values.
/// - initial: The action that supples an initial value.
///
/// - returns: The associated value for the specified key.
internal func associatedValue<T>(forKey key: StaticString = #function, initial: (Base) -> T) -> T {
let key = AssociationKey<T?>(key)
if let value = base.associations.value(forKey: key) {
return value
}
let value = initial(base)
base.associations.setValue(value, forKey: key)
return value
}
}
extension NSObjectProtocol {
@nonobjc internal var associations: Associations<Self> {
return Associations(self)
}
}
extension Associations {
/// Retrieve the associated value for the specified key.
///
/// - parameters:
/// - key: The key.
///
/// - returns: The associated value, or the default value if no value has been
/// associated with the key.
internal func value<Value>(forKey key: AssociationKey<Value>) -> Value {
return (objc_getAssociatedObject(base, key.address) as! Value?) ?? key.default
}
/// Retrieve the associated value for the specified key.
///
/// - parameters:
/// - key: The key.
///
/// - returns: The associated value, or `nil` if no value is associated with
/// the key.
internal func value<Value>(forKey key: AssociationKey<Value?>) -> Value? {
return objc_getAssociatedObject(base, key.address) as! Value?
}
/// Set the associated value for the specified key.
///
/// - parameters:
/// - value: The value to be associated.
/// - key: The key.
internal func setValue<Value>(_ value: Value, forKey key: AssociationKey<Value>) {
objc_setAssociatedObject(base, key.address, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Set the associated value for the specified key.
///
/// - parameters:
/// - value: The value to be associated.
/// - key: The key.
internal func setValue<Value>(_ value: Value?, forKey key: AssociationKey<Value?>) {
objc_setAssociatedObject(base, key.address, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Set the associated value for the specified key.
///
/// - parameters:
/// - value: The value to be associated.
/// - key: The key.
/// - address: The address of the object.
internal func unsafeSetAssociatedValue<Value>(_ value: Value?, forKey key: AssociationKey<Value>, forObjectAt address: UnsafeRawPointer) {
_rac_objc_setAssociatedObject(address, key.address, value, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
|
mit
|
bcfc0da9754f7c74403c11d6e668c8a2
| 30.725191 | 138 | 0.679981 | 3.648815 | false | false | false | false |
hulinSun/Better
|
better/better/Classes/Category/DiscoverModel.swift
|
1
|
2513
|
//
// DiscoverModel.swift
// better
//
// Created by Hony on 2016/10/26.
// Copyright © 2016年 Hony. All rights reserved.
//
import Foundation
import HandyJSON
//http://www.jianshu.com/p/cbed87d8656d
//http://open3.bantangapp.com/community/post/hotRecommend?app_id=com.jzyd.Better&app_installtime=1476251286&app_versions=1.5.1&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&device_token=711214f0edd8fe4444aa69d56119e0bbf83bc1675292e4b9e81b0a83a7cdff0a&oauth_token=1cfdf7dc28066c076c23269874460b58&os_versions=10.0.2&page=0&pagesize=18&screensize=750&track_device_info=iPhone7%2C2&track_deviceid=18B31DD0-2B1E-49A9-A78A-763C77FD65BD&track_user_id=2670024&v=14
/// 图片
class Pics: HandyJSON {
var url: String?
var tags: String?
var width: Double = 0
var height: Double = 0
required init() {} /// 如果定义是struct,连init()函数都不用声明;
}
/// 动态
class Dynamic: HandyJSON {
var comments: String?
var likes: String?
var is_collect: Bool = false
var is_like: Bool = false
var is_comment: Bool = false
required init() {}
}
/// 评论模型
class Comment:HandyJSON {
var id: String?
var user_id: String?
var username: String?
var nickname: String?
var avatar: String?
var conent: String?
var dateline: String?
var datestr: String?
var praise: String?
var reply: String?
var is_praise: Bool = false
var is_hot: Bool = false
var at_user: User?
var is_official: Bool = false
required init() {}
}
class Article: HandyJSON {
var id: String?
var content: String?
var author_id: String?
var type_id: String?
var post_type: String?
var relation_id: String?
var share_url: String?
var is_recommend: String?
var create_time: String?
var publish_time: String?
var datetime: String?
var datestr: String?
var mini_pic_url: String?
var middle_pic_url: String?
var author: User?
var pics: [Pics]?
var dynamic: [Dynamic]?
var comments: [Comment]?
var trace_id: String?
var brand_product: String?
var tags: [[String : AnyObject]]?
required init() {}
}
class DiscoverTopic: HandyJSON {
class DiscoverTopicData: HandyJSON {
var topic: [Topic]?
required init() {}
}
var status: String?
var msg: String?
var ts: String?
var data: DiscoverTopicData?
required init() {}
}
|
mit
|
80ec3a6a2983ad5e288b1a869cf90bc8
| 22.466667 | 501 | 0.659497 | 3.13486 | false | false | false | false |
argon/mas
|
MasKit/Commands/Upgrade.swift
|
1
|
2992
|
//
// Upgrade.swift
// mas-cli
//
// Created by Andrew Naylor on 30/12/2015.
// Copyright © 2015 Andrew Naylor. All rights reserved.
//
import Commandant
import CommerceKit
/// Command which upgrades apps with new versions available in the Mac App Store.
public struct UpgradeCommand: CommandProtocol {
public typealias Options = UpgradeOptions
public let verb = "upgrade"
public let function = "Upgrade outdated apps from the Mac App Store"
private let appLibrary: AppLibrary
/// Public initializer.
/// - Parameter appLibrary: AppLibrary manager.
public init() {
self.init(appLibrary: MasAppLibrary())
}
/// Internal initializer.
/// - Parameter appLibrary: AppLibrary manager.
init(appLibrary: AppLibrary = MasAppLibrary()) {
self.appLibrary = appLibrary
}
/// Runs the command.
public func run(_ options: Options) -> Result<(), MASError> {
let updateController = CKUpdateController.shared()
let updates: [CKUpdate]
let apps = options.apps
if apps.count > 0 {
// convert input into a list of appId's
let appIds: [UInt64]
appIds = apps.compactMap {
if let appId = UInt64($0) {
return appId
}
if let appId = appLibrary.appIdsByName[$0] {
return appId
}
return nil
}
// check each of those for updates
updates = appIds.compactMap {
updateController?.availableUpdate(withItemIdentifier: $0)
}
guard updates.count > 0 else {
printWarning("Nothing found to upgrade")
return .success(())
}
} else {
updates = updateController?.availableUpdates() ?? []
// Upgrade everything
guard updates.count > 0 else {
print("Everything is up-to-date")
return .success(())
}
}
print("Upgrading \(updates.count) outdated application\(updates.count > 1 ? "s" : ""):")
print(updates.map({ "\($0.title) (\($0.bundleVersion))" }).joined(separator: ", "))
let updateResults = updates.compactMap {
download($0.itemIdentifier.uint64Value)
}
switch updateResults.count {
case 0:
return .success(())
case 1:
return .failure(updateResults[0])
default:
return .failure(.downloadFailed(error: nil))
}
}
}
public struct UpgradeOptions: OptionsProtocol {
let apps: [String]
static func create(_ apps: [String]) -> UpgradeOptions {
return UpgradeOptions(apps: apps)
}
public static func evaluate(_ mode: CommandMode) -> Result<UpgradeOptions, CommandantError<MASError>> {
return create
<*> mode <| Argument(defaultValue: [], usage: "app(s) to upgrade")
}
}
|
mit
|
feccfb4487488ba73045c1656b24dc51
| 29.212121 | 107 | 0.570712 | 4.717666 | false | false | false | false |
zhangxigithub/elevator
|
Elevator/ElevatorControlPanel.swift
|
1
|
2790
|
//
// ElevatorControlPanel.swift
// Elevator
//
// Created by zhangxi on 12/17/15.
// Copyright © 2015 zhangxi.me. All rights reserved.
//
import UIKit
protocol ElevatorControlPanelDelegate
{
func up(panel:ElevatorControlPanel)
func down(panel:ElevatorControlPanel)
}
class ElevatorControlPanel: UIView {
var delegate:ElevatorControlPanelDelegate?
var floor:Int! //楼层号
var upButton:UIButton!
var downButton:UIButton!
var needUp = false //按下上行
{
didSet{
upButton.selected = needUp
}
}
var needDown = false //按下下行
{
didSet{
downButton.selected = needUp
}
}
var destination = false //目的地楼层,电梯内有人选了该楼层
convenience init(floor:Int,frame: CGRect) {
self.init(frame:frame)
//self.backgroundColor = UIColor.whiteColor()
//self.layer.borderColor = UIColor(white: 0.9, alpha: 1).CGColor
//self.layer.borderWidth = 1
self.floor = floor
let space:CGFloat = 2
let width = self.frame.size.width - space*2
let height = (self.frame.size.height - space)/2
upButton = UIButton(type: UIButtonType.Custom)
upButton.frame = CGRectMake(space, space, width, height)
upButton.setImage(UIImage(named: "up"), forState: UIControlState.Normal)
upButton.setImage(UIImage(named: "up_s"), forState: UIControlState.Selected)
upButton.addTarget(self, action: Selector("up:"), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(upButton)
downButton = UIButton(type: UIButtonType.Custom)
downButton.frame = CGRectMake(space,height+space, width, height)
downButton.setImage(UIImage(named: "down"), forState: UIControlState.Normal)
downButton.setImage(UIImage(named: "down_s"), forState: UIControlState.Selected)
downButton.addTarget(self, action: Selector("down:"), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(downButton)
}
func isBottomFloor()
{
downButton.hidden = true
}
func isTopFloor()
{
upButton.hidden = true
}
func up(button:UIButton)
{
//dispatch_async(dispatch_get_main_queue()) { () -> Void in
needUp = true
self.upButton.selected = true
self.delegate?.up(self)
//}
}
func down(button:UIButton)
{
//dispatch_async(dispatch_get_main_queue()) { () -> Void in
needDown = true
self.downButton.selected = true
self.delegate?.down(self)
//}
}
}
|
apache-2.0
|
de09e477bbcb5ac7d392132f6fa43cca
| 25.553398 | 110 | 0.601097 | 4.08209 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.