repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 202
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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
LonelyHusky/SCWeibo
|
SCWeibo/Classes/View/Home/View/SCStatusCell.swift
|
1
|
3289
|
//
// SCStatusCell.swift
// SCWeibo
//
// Created by 云卷云舒丶 on 16/7/23.
//
//
import UIKit
import SnapKit
//昵称文字大小
let SCtatusCellNameFontSize :CGFloat = 14
//头像大小
let SCStatusCellHeadImageWH :CGFloat = 35
//时间与来源
let SCStatusCellTimeFontSize : CGFloat = 10
//内容字体大小
let SCStatusCellContenFontSize : CGFloat = 14
//底部视图的高度
let SCStatusCellBottomViewH : CGFloat = 35
//间距
let SCStatusCellMargin : CGFloat = 10
class SCStatusCell: UITableViewCell {
// toolBar的顶部约束
var toolBarTopCons : Constraint?
var statusViewModel : SCStatusViewModel?{
didSet{
originalView.statusViewModel = statusViewModel
toolBarTopCons?.uninstall()
// 判断是否有转发weibo
if statusViewModel?.status?.retweeted_status != nil {
// 设置数据
retweetView.statusViewModel = statusViewModel
// 有转发微博
retweetView.hidden = false
toolBar.snp_updateConstraints(closure: { (make) in
toolBarTopCons = make.top.equalTo(retweetView.snp_bottom).constraint
})
}else{
// 没有转发微博
// 隐藏视图
retweetView.hidden = true
toolBar.snp_updateConstraints(closure: { (make) in
toolBarTopCons = make.top.equalTo(originalView.snp_bottom).constraint
})
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI(){
// cell选中的样式
selectionStyle = .None
backgroundColor = UIColor (white: 242/255,alpha:1)
// 添加控件
contentView.addSubview(originalView)
contentView.addSubview(toolBar)
contentView.addSubview(retweetView)
// 添加约束
originalView.snp_makeConstraints { (make) in
make.top.equalTo(contentView).offset(SCStatusCellMargin)
make.trailing.leading.equalTo(contentView)
}
toolBar.snp_makeConstraints { (make) in
toolBarTopCons = make.top.equalTo(retweetView.snp_bottom).constraint
make.leading.trailing.equalTo(originalView)
make.height.equalTo(SCStatusCellBottomViewH)
}
retweetView.snp_makeConstraints { (make) in
make.leading.trailing.equalTo(originalView)
make.top.equalTo(originalView.snp_bottom)
// make.height.equalTo(60)
}
contentView.snp_makeConstraints { (make) in
make.bottom.equalTo(self.toolBar.snp_bottom)
make.top.leading.trailing.equalTo(self)
}
}
private lazy var originalView:SCOriginalStatusView = SCOriginalStatusView()
private lazy var toolBar: SCStatusToolBar = SCStatusToolBar()
private lazy var retweetView :SCRetweetStatusView = SCRetweetStatusView()
}
|
mit
|
48ac933573b84514d784473804138032
| 26.464912 | 88 | 0.611306 | 4.557496 | false | false | false | false |
ryuichis/swift-ast
|
Sources/AST/Type/TupleType.swift
|
2
|
1914
|
/*
Copyright 2016-2018 Ryuichi Intellectual Property and the Yanagiba project contributors
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.
*/
public class TupleType : TypeBase {
public struct Element {
public let type: Type
public let name: Identifier?
public let attributes: Attributes
public let isInOutParameter: Bool
public init(type: Type) {
self.type = type
self.name = nil
self.attributes = []
self.isInOutParameter = false
}
public init(
type: Type,
name: Identifier,
attributes: Attributes = [],
isInOutParameter: Bool = false
) {
self.name = name
self.type = type
self.attributes = attributes
self.isInOutParameter = isInOutParameter
}
}
public let elements: [Element]
public init(elements: [Element]) {
self.elements = elements
}
// MARK: - ASTTextRepresentable
override public var textDescription: String {
return "(\(elements.map({ $0.textDescription }).joined(separator: ", ")))"
}
}
extension TupleType.Element : ASTTextRepresentable {
public var textDescription: String {
let attr = attributes.isEmpty ? "" : "\(attributes.textDescription) "
let inoutStr = isInOutParameter ? "inout " : ""
var nameStr = ""
if let name = name {
nameStr = "\(name): "
}
return "\(nameStr)\(attr)\(inoutStr)\(type.textDescription)"
}
}
|
apache-2.0
|
bc9aeda8378c9ddaae7e21451cf320ac
| 27.567164 | 90 | 0.675026 | 4.546318 | false | false | false | false |
TMTBO/TTARefresher
|
TTARefresher/Classes/Header/TTARefresherNormalHeader.swift
|
1
|
3835
|
//
// TTARefresherNormalHeader.swift
// Pods
//
// Created by TobyoTenma on 12/05/2017.
//
//
import UIKit
open class TTARefresherNormalHeader: TTARefresherStateHeader {
public var indicatotStyle = UIActivityIndicatorViewStyle.gray {
didSet {
loadingView = nil
setNeedsLayout()
}
}
public lazy var arrowImageView: UIImageView = {
let arrowImage = Bundle.TTARefresher.arrowImage()
let arrowImageView = UIImageView(image: arrowImage)
self.addSubview(arrowImageView)
return arrowImageView
}()
lazy var loadingView: UIActivityIndicatorView? = {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: self.indicatotStyle)
indicator.hidesWhenStopped = true
self.addSubview(indicator)
return indicator
}()
open override var state: TTARefresherState {
didSet {
if oldValue == state { return }
if state == .idle {
if oldValue == .refreshing {
arrowImageView.transform = .identity
UIView.animate(withDuration: TTARefresherAnimationDuration.slow, animations: { [weak self] in
guard let `self` = self else { return }
self.loadingView?.alpha = 0
}, completion: { [weak self] (isFinished) in
guard let `self` = self else { return }
if self.state != .idle { return }
self.loadingView?.alpha = 1
self.loadingView?.stopAnimating()
self.arrowImageView.isHidden = false
})
} else {
loadingView?.stopAnimating()
arrowImageView.isHidden = false
UIView.animate(withDuration: TTARefresherAnimationDuration.fast, animations: { [weak self] in
guard let `self` = self else { return }
self.arrowImageView.transform = .identity
})
}
} else if state == .pulling {
loadingView?.stopAnimating()
arrowImageView.isHidden = false
UIView.animate(withDuration: TTARefresherAnimationDuration.fast, animations: { [weak self] in
guard let `self` = self else { return }
self.arrowImageView.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat.pi)
})
} else if state == .refreshing {
loadingView?.alpha = 1
loadingView?.startAnimating()
arrowImageView.isHidden = true
}
}
}
}
// MARK: - Override Methods
extension TTARefresherNormalHeader {
override open func placeSubviews() {
super.placeSubviews()
var arrowCenterX = bounds.width * 0.5
if !stateLabel.isHidden {
let stateWidth = stateLabel.ttaRefresher.textWidth()
var timeWidth: CGFloat = 0
if !lastUpdatedTimeLabel.isHidden {
timeWidth = lastUpdatedTimeLabel.ttaRefresher.textWidth()
}
let textWidth = max(stateWidth, timeWidth)
arrowCenterX -= textWidth / 2 + labelLeftInset
}
let arrowCenterY = bounds.height * 0.5
let arrowCenter = CGPoint(x: arrowCenterX, y: arrowCenterY)
if arrowImageView.constraints.count == 0, let image = arrowImageView.image {
arrowImageView.bounds.size = image.size
arrowImageView.center = arrowCenter
}
if loadingView?.constraints.count == 0 {
loadingView?.center = arrowCenter
}
arrowImageView.tintColor = stateLabel.textColor
}
}
|
mit
|
e222b7b77cde3495195dc4a2e05ed6a4
| 36.598039 | 113 | 0.56558 | 5.681481 | false | false | false | false |
dterana/Pokedex-API
|
Sources/App/Models/Pokemon.swift
|
1
|
2837
|
import Vapor
import Fluent
final class Pokemon: Model {
var id: Node?
var exists: Bool = false
var index: String
var name: String
var type: String
var baseDefense: Int
var baseAttack: Int
var height: Int
var weight: Int
var evoLvl: Int
var evoIndex: String
var description: String
//Attention - Postgresql field name are only full lowcase
init(index: String, name: String, type: String, basedefense: Int, baseattack: Int, height: Int, weight: Int, evolvl: Int, evoindex: String, description: String) {
self.id = nil
self.index = index
self.name = name
self.type = type
self.baseDefense = basedefense
self.baseAttack = baseattack
self.height = height
self.weight = weight
self.evoLvl = evolvl
self.evoIndex = evoindex
self.description = description
}
//Attention - Postgresql field name are only full lowcase
init(node: Node, in context: Context) throws {
id = try node.extract("id")
index = try node.extract("index")
name = try node.extract("name")
type = try node.extract("type")
baseDefense = try node.extract("basedefense")
baseAttack = try node.extract("baseattack")
height = try node.extract("height")
weight = try node.extract("weight")
evoLvl = try node.extract("evolvl")
evoIndex = try node.extract("evoindex")
description = try node.extract("description")
}
//Attention - Postgresql field name are only full lowcase
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"index": index,
"name": name,
"type": type,
"basedefense": baseDefense,
"baseattack": baseAttack,
"height": height,
"weight": weight,
"evolvl": evoLvl,
"evoindex": evoIndex,
"description": description
])
}
//Attention - Postgresql field name are only full lowcase
static func prepare(_ database: Database) throws {
try database.create("pokemons") { users in
users.id()
users.string("index")
users.string("name")
users.string("type")
users.int("basedefense")
users.int("baseattack")
users.int("height")
users.int("weight")
users.int("evolvl")
users.string("evoindex")
users.string("description")
}
}
static func revert(_ database: Database) throws {
try database.delete("pokemons")
}
}
extension Pokemon {
func types() throws -> Siblings<Type> {
return try siblings()
}
}
|
mit
|
403d0e58dc669435388235983f47b1ac
| 27.94898 | 166 | 0.568558 | 4.331298 | false | false | false | false |
Drusy/auvergne-webcams-ios
|
Carthage/Checkouts/Siren/Example/Example/AppDelegate.swift
|
1
|
4990
|
//
// AppDelegate.swift
// Siren
//
// Created by Arthur Sabintsev on 1/3/15.
// Copyright (c) 2015 Sabintsev iOS Projects. All rights reserved.
//
import UIKit
import Siren
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
window?.makeKeyAndVisible()
setupSiren()
return true
}
func setupSiren() {
let siren = Siren.shared
// Optional
siren.delegate = self
// Optional
siren.debugEnabled = true
// Optional - Change the name of your app. Useful if you have a long app name and want to display a shortened version in the update dialog (e.g., the UIAlertController).
// siren.appName = "Test App Name"
// Optional - Change the various UIAlertController and UIAlertAction messaging. One or more values can be changes. If only a subset of values are changed, the defaults with which Siren comes with will be used.
// siren.alertMessaging = SirenAlertMessaging(updateTitle: NSAttributedString(string: "New Fancy Title"),
// updateMessage: NSAttributedString(string: "New message goes here!"),
// updateButtonMessage: NSAttributedString(string: "Update Now, Plz!?"),
// nextTimeButtonMessage: NSAttributedString(string: "OK, next time it is!"),
// skipVersionButtonMessage: NSAttributedString(string: "Please don't push skip, please don't!"))
// Optional - Defaults to .Option
// siren.alertType = .option // or .force, .skip, .none
// Optional - Can set differentiated Alerts for Major, Minor, Patch, and Revision Updates (Must be called AFTER siren.alertType, if you are using siren.alertType)
siren.majorUpdateAlertType = .option
siren.minorUpdateAlertType = .option
siren.patchUpdateAlertType = .option
siren.revisionUpdateAlertType = .option
// Optional - Sets all messages to appear in Russian. Siren supports many other languages, not just English and Russian.
// siren.forceLanguageLocalization = .russian
// Optional - Set this variable if your app is not available in the U.S. App Store. List of codes: https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/Chapters/AppStoreTerritories.html
// siren.countryCode = ""
// Optional - Set this variable if you would only like to show an alert if your app has been available on the store for a few days.
// This default value is set to 1 to avoid this issue: https://github.com/ArtSabintsev/Siren#words-of-caution
// To show the update immediately after Apple has updated their JSON, set this value to 0. Not recommended due to aforementioned reason in https://github.com/ArtSabintsev/Siren#words-of-caution.
siren.showAlertAfterCurrentVersionHasBeenReleasedForDays = 0
// Optional (Only do this if you don't call checkVersion in didBecomeActive)
// siren.checkVersion(checkType: .immediately)
}
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.
Siren.shared.checkVersion(checkType: .daily)
}
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.
Siren.shared.checkVersion(checkType: .daily)
}
}
extension AppDelegate: SirenDelegate
{
func sirenDidShowUpdateDialog(alertType: Siren.AlertType) {
print(#function, alertType)
}
func sirenUserDidCancel() {
print(#function)
}
func sirenUserDidSkipVersion() {
print(#function)
}
func sirenUserDidLaunchAppStore() {
print(#function)
}
func sirenDidFailVersionCheck(error: Error) {
print(#function, error)
}
func sirenLatestVersionInstalled() {
print(#function, "Latest version of app is installed")
}
func sirenNetworkCallDidReturnWithNewVersionInformation(lookupModel: SirenLookupModel) {
print(#function, "\(lookupModel)")
}
// This delegate method is only hit when alertType is initialized to .none
func sirenDidDetectNewVersionWithoutAlert(title: String, message: String, updateType: UpdateType) {
print(#function, "\n\(title)\n\(message).\nRelease type: \(updateType.rawValue.capitalized)")
}
}
|
apache-2.0
|
597ae9ea7fd644fbe2ca5e0a50eb0f90
| 43.159292 | 248 | 0.678557 | 5.020121 | false | false | false | false |
dreamsxin/swift
|
test/IRGen/lazy_multi_file.swift
|
3
|
924
|
// RUN: %target-swift-frontend -primary-file %s %S/Inputs/lazy_multi_file_helper.swift -emit-ir | FileCheck %s
// REQUIRES: CPU=i386_or_x86_64
// CHECK: %C15lazy_multi_file8Subclass = type <{ %swift.refcounted, %[[OPTIONAL_INT_TY:GSqSi_]], [{{[0-9]+}} x i8], %SS }>
// CHECK: %[[OPTIONAL_INT_TY]] = type <{ [{{[0-9]+}} x i8], [1 x i8] }>
// CHECK: %V15lazy_multi_file13LazyContainer = type <{ %[[OPTIONAL_INT_TY]] }>
class Subclass : LazyContainerClass {
final var str = "abc"
// CHECK-LABEL: @_TFC15lazy_multi_file8Subclass6getStrfT_SS(%C15lazy_multi_file8Subclass*) {{.*}} {
func getStr() -> String {
// CHECK: = getelementptr inbounds %C15lazy_multi_file8Subclass, %C15lazy_multi_file8Subclass* %0, i32 0, i32 3
return str
}
}
// CHECK-LABEL: @_TF15lazy_multi_file4testFT_Si() {{.*}} {
func test() -> Int {
var container = LazyContainer()
useLazyContainer(container)
return container.lazyVar
}
|
apache-2.0
|
acefb57e85ed113d7e6768be40297ad0
| 37.5 | 122 | 0.658009 | 2.942675 | false | true | false | false |
dreamsxin/swift
|
test/decl/protocol/conforms/near_miss_objc.swift
|
2
|
5760
|
// RUN: %target-parse-verify-swift
// Test "near misses" where a member of a class or extension thereof
// nearly matches an optional requirement, but does not exactly match.
@objc protocol P1 {
@objc optional func doSomething(a: Int, b: Double) // expected-note 2{{requirement 'doSomething(a:b:)' declared here}}
}
class C1a : P1 {
@objc func doSomething(a: Int, c: Double) { }
// expected-warning@-1{{instance method 'doSomething(a:c:)' nearly matches optional requirement 'doSomething(a:b:)' of protocol 'P1'}}
// expected-note@-2{{rename to 'doSomething(a:b:)' to satisfy this requirement}}{{34-34=b }}{{none}}
// expected-note@-3{{move 'doSomething(a:c:)' to an extension to silence this warning}}
// expected-note@-4{{make 'doSomething(a:c:)' private to silence this warning}}{{9-9=private }}
}
class C1b : P1 {
}
extension C1b {
@objc func doSomething(a: Int, c: Double) { } // don't warn
}
class C1c {
}
extension C1c : P1 {
func doSomething(a: Int, c: Double) { }
// expected-warning@-1{{instance method 'doSomething(a:c:)' nearly matches optional requirement 'doSomething(a:b:)' of protocol 'P1'}}
// expected-note@-2{{rename to 'doSomething(a:b:)' to satisfy this requirement}}{{28-28=b }}{{none}}
// expected-note@-3{{move 'doSomething(a:c:)' to another extension to silence this warning}}
// expected-note@-4{{make 'doSomething(a:c:)' private to silence this warning}}{{3-3=private }}
}
class C1d : P1 {
@objc private func doSomething(a: Int, c: Double) { } // don't warn
}
class C1e : P1 {
@nonobjc func doSomething(a: Int, c: Double) { } // don't warn
}
// Don't try to match an optional requirement against a declaration
// that already satisfies one witness.
@objc protocol P2 {
@objc optional func doSomething(a: Int, b: Double)
@objc optional func doSomething(a: Int, d: Double)
}
class C2a : P2 {
@objc func doSomething(a: Int, b: Double) { } // don't warn: this matches something
}
// Cope with base names that change.
@objc protocol P3 {
@objc optional func doSomethingWithPriority(_ a: Int, d: Double) // expected-note{{requirement 'doSomethingWithPriority(_:d:)' declared here}}
}
class C3a : P3 {
func doSomething(priority: Int, d: Double) { }
// expected-warning@-1{{instance method 'doSomething(priority:d:)' nearly matches optional requirement 'doSomethingWithPriority(_:d:)' of protocol 'P3'}}
// expected-note@-2{{rename to 'doSomethingWithPriority(_:d:)' to satisfy this requirement}}{{20-20=_ }}
// expected-note@-3{{move 'doSomething(priority:d:)' to an extension to silence this warning}}
// expected-note@-4{{make 'doSomething(priority:d:)' private to silence this warning}}{{3-3=private }}
}
@objc protocol P4 {
@objc optional func doSomething(priority: Int, d: Double) // expected-note{{requirement 'doSomething(priority:d:)' declared here}}
}
class C4a : P4 {
func doSomethingWithPriority(_ a: Int, d: Double) { }
// expected-warning@-1{{instance method 'doSomethingWithPriority(_:d:)' nearly matches optional requirement 'doSomething(priority:d:)' of protocol 'P4'}}
// expected-note@-2{{rename to 'doSomething(priority:d:)' to satisfy this requirement}}{{32-33=priority}}
// expected-note@-3{{move 'doSomethingWithPriority(_:d:)' to an extension to silence this warning}}
// expected-note@-4{{make 'doSomethingWithPriority(_:d:)' private to silence this warning}}{{3-3=private }}
}
@objc class SomeClass { }
@objc protocol P5 {
@objc optional func methodWithInt(_: Int, forSomeClass: SomeClass, dividingDouble: Double)
// expected-note@-1{{requirement 'methodWithInt(_:forSomeClass:dividingDouble:)' declared here}}
}
class C5a : P5 {
func method(_: Int, for someClass: SomeClass, dividing double: Double) { }
// expected-warning@-1{{instance method 'method(_:for:dividing:)' nearly matches optional requirement 'methodWithInt(_:forSomeClass:dividingDouble:)' of protocol 'P5'}}
// expected-note@-2{{rename to 'methodWithInt(_:forSomeClass:dividingDouble:)' to satisfy this requirement}}{{8-14=methodWithInt}}{{23-26=forSomeClass}}{{49-57=dividingDouble}}{{none}}
// expected-note@-3{{move 'method(_:for:dividing:)' to an extension to silence this warning}}
// expected-note@-4{{make 'method(_:for:dividing:)' private to silence this warning}}{{3-3=private }}
}
@objc protocol P6 {
@objc optional func method(_: Int, for someClass: SomeClass, dividing double: Double)
// expected-note@-1{{requirement 'method(_:for:dividing:)' declared here}}
}
class C6a : P6 {
func methodWithInt(_: Int, forSomeClass: SomeClass, dividingDouble: Double) { }
// expected-warning@-1{{instance method 'methodWithInt(_:forSomeClass:dividingDouble:)' nearly matches optional requirement 'method(_:for:dividing:)' of protocol 'P6'}}
// expected-note@-2{{rename to 'method(_:for:dividing:)' to satisfy this requirement}}{{8-21=method}}{{30-30=for }}{{55-55=dividing }}{{none}}
// expected-note@-3{{move 'methodWithInt(_:forSomeClass:dividingDouble:)' to an extension to silence this warning}}
// expected-note@-4{{make 'methodWithInt(_:forSomeClass:dividingDouble:)' private to silence this warning}}{{3-3=private }}
}
// Use the first note to always describe why it didn't match.
@objc protocol P7 {
@objc optional func method(foo: Float)
// expected-note@-1{{requirement 'method(foo:)' declared here}}
}
class C7a : P7 {
@objc func method(foo: Double) { }
// expected-warning@-1{{instance method 'method(foo:)' nearly matches optional requirement 'method(foo:)' of protocol 'P7'}}
// expected-note@-2{{candidate has non-matching type '(foo: Double) -> ()'}}
// expected-note@-3{{move 'method(foo:)' to an extension to silence this warning}}
// expected-note@-4{{make 'method(foo:)' private to silence this warning}}
}
|
apache-2.0
|
63479d628a2dfce71875a9136da0b46c
| 46.603306 | 186 | 0.701563 | 3.66879 | false | false | false | false |
haskellswift/swift-package-manager
|
Tests/FunctionalTests/ModuleMapTests.swift
|
2
|
2644
|
/*
This source file is part of the Swift.org open source project
Copyright 2015 - 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 Swift project authors
*/
import XCTest
import TestSupport
import Basic
import Utility
import func POSIX.popen
#if os(macOS)
private let dylib = "dylib"
#else
private let dylib = "so"
#endif
class ModuleMapsTestCase: XCTestCase {
private func fixture(name: String, cModuleName: String, rootpkg: String, body: @escaping (AbsolutePath, [String]) throws -> Void) {
TestSupport.fixture(name: name) { prefix in
let input = prefix.appending(components: cModuleName, "C", "foo.c")
let outdir = prefix.appending(components: rootpkg, ".build", "debug")
try makeDirectories(outdir)
let output = outdir.appending(component: "libfoo.\(dylib)")
try systemQuietly(["clang", "-shared", input.asString, "-o", output.asString])
var Xld = ["-L", outdir.asString]
#if os(Linux)
Xld += ["-rpath", outdir.asString]
#endif
try body(prefix, Xld)
}
}
func testDirectDependency() {
fixture(name: "ModuleMaps/Direct", cModuleName: "CFoo", rootpkg: "App") { prefix, Xld in
XCTAssertBuilds(prefix.appending(component: "App"), Xld: Xld)
let debugout = try popen([prefix.appending(RelativePath("App/.build/debug/App")).asString])
XCTAssertEqual(debugout, "123\n")
let releaseout = try popen([prefix.appending(RelativePath("App/.build/release/App")).asString])
XCTAssertEqual(releaseout, "123\n")
}
}
func testTransitiveDependency() {
fixture(name: "ModuleMaps/Transitive", cModuleName: "packageD", rootpkg: "packageA") { prefix, Xld in
XCTAssertBuilds(prefix.appending(component: "packageA"), Xld: Xld)
func verify(_ conf: String, file: StaticString = #file, line: UInt = #line) throws {
let expectedOutput = "calling Y.bar()\nY.bar() called\nX.foo() called\n123\n"
let out = try popen([prefix.appending(components: "packageA", ".build", conf, "packageA").asString])
XCTAssertEqual(out, expectedOutput)
}
try verify("debug")
try verify("release")
}
}
static var allTests = [
("testDirectDependency", testDirectDependency),
("testTransitiveDependency", testTransitiveDependency),
]
}
|
apache-2.0
|
4d08f26b4a10d34aa62ef30a3f74b4a4
| 33.789474 | 135 | 0.636914 | 4.170347 | false | true | false | false |
JadenGeller/CS-81-Project
|
Sources/DecimalDigit.swift
|
1
|
696
|
//
// DecimalDigit.swift
// Language
//
// Created by Jaden Geller on 2/22/16.
// Copyright © 2016 Jaden Geller. All rights reserved.
//
public enum DecimalDigit: Int, Equatable {
case Zero
case One
case Two
case Three
case Four
case Five
case Six
case Seven
case Eight
case Nine
}
extension DecimalDigit: IntegerLiteralConvertible {
public init(integerLiteral value: Int) {
guard let this = DecimalDigit(rawValue: value) else {
fatalError("Decimal digit must be between 0 and 9")
}
self = this
}
}
public func ==(lhs: DecimalDigit, rhs: DecimalDigit) -> Bool {
return lhs.rawValue == rhs.rawValue
}
|
mit
|
18073f4c37038e27b3ddcdf0304220be
| 20.060606 | 63 | 0.641727 | 4.088235 | false | false | false | false |
ben-ng/swift
|
validation-test/compiler_crashers_fixed/00969-swift-diagnosticengine-flushactivediagnostic.swift
|
1
|
1054
|
// 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 https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
return ""a<T>) + seq: T>(n: d = F>()
class func a
extension Array {
}
func e()
typealias F = Int])
A>(Any) {
() -> Any in
typealias F>] = b<T -> () -> V>(b> {
class func f()
}
func a<c]()
func g() -> (#object1, Any)
func g: A, a
struct c == 0.C(Range(a")
class B {
import Foundation
public class d<T {
typealias e, g<T -> {
}
func call(t: B? {
protocol d where h, f(A, Any, k : B>) {
let a {
print(a(true {
}
print(Any, let v: [B
func d>(a)
func b(")
}
}
struct c<T where B : a {
class A : C {
protocol P {}
extension NSSet {
enum S<U -> {
return self.h : A, range.B
}
}
return true
func e: d where H) {
private class func a: Sequence> {
}
}
}
}
}
}
retur
|
apache-2.0
|
f0778945f987793e706eaba3f4d197b2
| 17.821429 | 79 | 0.637571 | 2.803191 | false | false | false | false |
josve05a/wikipedia-ios
|
Wikipedia/Code/ReadingThemesControlsViewController.swift
|
2
|
11696
|
import UIKit
protocol WMFReadingThemesControlsViewControllerDelegate: class {
func fontSizeSliderValueChangedInController(_ controller: ReadingThemesControlsViewController, value: Int)
func toggleSyntaxHighlighting(_ controller: ReadingThemesControlsViewController)
}
@objc(WMFReadingThemesControlsViewController)
class ReadingThemesControlsViewController: UIViewController {
@objc static let WMFUserDidSelectThemeNotification = "WMFUserDidSelectThemeNotification"
@objc static let WMFUserDidSelectThemeNotificationThemeNameKey = "themeName"
@objc static let WMFUserDidSelectThemeNotificationIsImageDimmingEnabledKey = "isImageDimmingEnabled"
@objc static let nibName = "ReadingThemesControlsViewController"
var theme = Theme.standard
@IBOutlet fileprivate var slider: SWStepSlider!
fileprivate var maximumValue: Int?
fileprivate var currentValue: Int?
@IBOutlet weak var brightnessSlider: UISlider!
@IBOutlet weak var lightThemeButton: UIButton!
@IBOutlet weak var sepiaThemeButton: UIButton!
@IBOutlet weak var darkThemeButton: UIButton!
@IBOutlet weak var blackThemeButton: UIButton!
@IBOutlet var separatorViews: [UIView]!
@IBOutlet var textSizeSliderViews: [UIView]!
@IBOutlet weak var minBrightnessImageView: UIImageView!
@IBOutlet weak var maxBrightnessImageView: UIImageView!
@IBOutlet weak var tSmallImageView: UIImageView!
@IBOutlet weak var tLargeImageView: UIImageView!
@IBOutlet var stackView: UIStackView!
@IBOutlet var lastSeparator: UIView!
@IBOutlet var syntaxHighlightingContainerView: UIView!
@IBOutlet var syntaxHighlightingLabel: UILabel!
@IBOutlet var syntaxHighlightingSwitch: UISwitch!
var visible = false
var showsSyntaxHighlighting: Bool = false {
didSet {
evaluateShowsSyntaxHighlightingState()
updatePreferredContentSize()
}
}
open weak var delegate: WMFReadingThemesControlsViewControllerDelegate?
open override func viewDidLoad() {
super.viewDidLoad()
if let max = self.maximumValue {
if let current = self.currentValue {
self.setValues(0, maximum: max, current: current)
self.maximumValue = nil
self.currentValue = nil
}
}
brightnessSlider.value = Float(UIScreen.main.brightness)
brightnessSlider.accessibilityLabel = WMFLocalizedString("reading-themes-controls-accessibility-brightness-slider", value: "Brightness slider", comment: "Accessibility label for the brightness slider in the Reading Themes Controls popover")
lightThemeButton.accessibilityLabel = WMFLocalizedString("reading-themes-controls-accessibility-light-theme-button", value: "Light theme", comment: "Accessibility label for the light theme button in the Reading Themes Controls popover")
sepiaThemeButton.accessibilityLabel = WMFLocalizedString("reading-themes-controls-accessibility-sepia-theme-button", value: "Sepia theme", comment: "Accessibility label for the sepia theme button in the Reading Themes Controls popover")
darkThemeButton.accessibilityLabel = WMFLocalizedString("reading-themes-controls-accessibility-dark-theme-button", value: "Dark theme", comment: "Accessibility label for the dark theme button in the Reading Themes Controls popover")
blackThemeButton.accessibilityLabel = WMFLocalizedString("reading-themes-controls-accessibility-black-theme-button", value: "Black theme", comment: "Accessibility label for the black theme button in the Reading Themes Controls popover")
lightThemeButton.backgroundColor = Theme.light.colors.paperBackground
sepiaThemeButton.backgroundColor = Theme.sepia.colors.paperBackground
darkThemeButton.backgroundColor = Theme.dark.colors.paperBackground
blackThemeButton.backgroundColor = Theme.black.colors.paperBackground
lightThemeButton.setTitleColor(Theme.light.colors.primaryText, for: .normal)
sepiaThemeButton.setTitleColor(Theme.sepia.colors.primaryText, for: .normal)
darkThemeButton.setTitleColor(Theme.dark.colors.primaryText, for: .normal)
blackThemeButton.setTitleColor(Theme.black.colors.primaryText, for: .normal)
for slideView in textSizeSliderViews {
slideView.accessibilityLabel = CommonStrings.textSizeSliderAccessibilityLabel
}
syntaxHighlightingLabel.text = WMFLocalizedString("reading-themes-controls-syntax-highlighting", value: "Syntax Highlighting", comment: "Text for syntax highlighting label in the Reading Themes Controls popover")
syntaxHighlightingLabel.isAccessibilityElement = false
syntaxHighlightingSwitch.accessibilityLabel = WMFLocalizedString("reading-themes-controls-accessibility-syntax-highlighting-switch", value: "Syntax Highlighting", comment: "Accessibility text for the syntax highlighting toggle in the Reading Themes Controls popover")
NotificationCenter.default.addObserver(self, selector: #selector(self.screenBrightnessChangedInApp(notification:)), name: UIScreen.brightnessDidChangeNotification, object: nil)
updateFonts()
evaluateShowsSyntaxHighlightingState()
evaluateSyntaxHighlightingSelectedState()
updatePreferredContentSize()
}
deinit {
NotificationCenter.default.removeObserver(self)
NSObject.cancelPreviousPerformRequests(withTarget: self)
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
func applyBorder(to button: UIButton) {
button.borderWidth = 2
button.isEnabled = false
button.borderColor = theme.colors.link
button.accessibilityTraits = UIAccessibilityTraits.selected
}
func removeBorderFrom(_ button: UIButton) {
button.borderWidth = traitCollection.displayScale > 0.0 ? 1.0/traitCollection.displayScale : 0.5
button.isEnabled = true
button.borderColor = theme.colors.border
button.accessibilityTraits = UIAccessibilityTraits.button
}
var isTextSizeSliderHidden: Bool {
set {
let _ = self.view //ensure view is loaded
for slideView in textSizeSliderViews {
slideView.isHidden = newValue
}
updatePreferredContentSize()
}
get {
return textSizeSliderViews.first?.isHidden ?? false
}
}
@objc open func setValuesWithSteps(_ steps: Int, current: Int) {
if self.isViewLoaded {
self.setValues(0, maximum: steps-1, current: current)
}else{
maximumValue = steps-1
currentValue = current
}
}
func setValues(_ minimum: Int, maximum: Int, current: Int){
self.slider.minimumValue = minimum
self.slider.maximumValue = maximum
self.slider.value = current
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
visible = true
let currentTheme = UserDefaults.wmf.theme(compatibleWith: traitCollection)
apply(theme: currentTheme)
}
open override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
updateFonts()
}
private func updateFonts() {
syntaxHighlightingLabel.font = UIFont.wmf_font(.body, compatibleWithTraitCollection: traitCollection)
}
@objc func screenBrightnessChangedInApp(notification: Notification){
brightnessSlider.value = Float(UIScreen.main.brightness)
}
@objc fileprivate func _logBrightnessChange() {
}
fileprivate func logBrightnessChange() {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(_logBrightnessChange), object: nil)
self.perform(#selector(_logBrightnessChange), with: nil, afterDelay: 0.3, inModes: [RunLoop.Mode.default])
}
fileprivate func updatePreferredContentSize() {
preferredContentSize = stackView.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)
}
fileprivate func evaluateShowsSyntaxHighlightingState() {
lastSeparator.isHidden = !showsSyntaxHighlighting
syntaxHighlightingContainerView.isHidden = !showsSyntaxHighlighting
}
fileprivate func evaluateSyntaxHighlightingSelectedState() {
syntaxHighlightingSwitch.isOn = UserDefaults.wmf.wmf_IsSyntaxHighlightingEnabled
}
@IBAction func brightnessSliderValueChanged(_ sender: UISlider) {
UIScreen.main.brightness = CGFloat(sender.value)
logBrightnessChange()
}
@IBAction func fontSliderValueChanged(_ slider: SWStepSlider) {
if let delegate = self.delegate, visible {
delegate.fontSizeSliderValueChangedInController(self, value: self.slider.value)
}
}
func userDidSelect(theme: Theme) {
let userInfo = [ReadingThemesControlsViewController.WMFUserDidSelectThemeNotificationThemeNameKey: theme.name]
NotificationCenter.default.post(name: Notification.Name(ReadingThemesControlsViewController.WMFUserDidSelectThemeNotification), object: nil, userInfo: userInfo)
}
@IBAction func sepiaThemeButtonPressed(_ sender: Any) {
userDidSelect(theme: Theme.sepia)
}
@IBAction func lightThemeButtonPressed(_ sender: Any) {
userDidSelect(theme: Theme.light)
}
@IBAction func darkThemeButtonPressed(_ sender: Any) {
userDidSelect(theme: Theme.dark.withDimmingEnabled(UserDefaults.wmf.wmf_isImageDimmingEnabled))
}
@IBAction func blackThemeButtonPressed(_ sender: Any) {
userDidSelect(theme: Theme.black.withDimmingEnabled(UserDefaults.wmf.wmf_isImageDimmingEnabled))
}
@IBAction func syntaxHighlightingSwitched(_ sender: UISwitch) {
delegate?.toggleSyntaxHighlighting(self)
UserDefaults.wmf.wmf_IsSyntaxHighlightingEnabled = sender.isOn
}
}
// MARK: - Themeable
extension ReadingThemesControlsViewController: Themeable {
public func apply(theme: Theme) {
self.theme = theme
view.backgroundColor = theme.colors.popoverBackground
for separator in separatorViews {
separator.backgroundColor = theme.colors.border
}
slider.backgroundColor = view.backgroundColor
removeBorderFrom(lightThemeButton)
removeBorderFrom(darkThemeButton)
removeBorderFrom(sepiaThemeButton)
removeBorderFrom(blackThemeButton)
switch theme.name {
case Theme.sepia.name:
applyBorder(to: sepiaThemeButton)
case Theme.light.name:
applyBorder(to: lightThemeButton)
case Theme.darkDimmed.name:
fallthrough
case Theme.dark.name:
applyBorder(to: darkThemeButton)
case Theme.blackDimmed.name:
fallthrough
case Theme.black.name:
applyBorder(to: blackThemeButton)
default:
break
}
minBrightnessImageView.tintColor = theme.colors.secondaryText
maxBrightnessImageView.tintColor = theme.colors.secondaryText
tSmallImageView.tintColor = theme.colors.secondaryText
tLargeImageView.tintColor = theme.colors.secondaryText
syntaxHighlightingLabel.textColor = theme.colors.primaryText
view.tintColor = theme.colors.link
}
}
|
mit
|
710645f3a4daeb61f088c2bcecf46c2f
| 41.530909 | 275 | 0.711269 | 5.419833 | false | false | false | false |
nathantannar4/NTComponents
|
NTComponents/UI Kit/TabBar/NTTabBarItem.swift
|
1
|
4738
|
//
// NTTabBarItem.swift
// NTComponents
//
// Copyright © 2017 Nathan Tannar.
//
// 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.
//
// Created by Nathan Tannar on 2/12/17.
//
public protocol NTTabBarItemDelegate: NSObjectProtocol {
func tabBarItem(didSelect item: NTTabBarItem)
}
open class NTTabBarItem: NTAnimatedView {
open var title: String? {
get {
return titleLabel.text
}
set {
titleLabel.text = newValue
}
}
open var image: UIImage? {
get {
return imageView.image?.withRenderingMode(.alwaysTemplate)
}
set {
imageView.image = newValue?.withRenderingMode(.alwaysTemplate)
}
}
open var selectedImage: UIImage?
open var titleLabel: NTLabel = {
let label = NTLabel(style: .caption)
label.textAlignment = .center
label.font = Font.Default.Subhead.withSize(11)
label.textColor = Color.Gray.P500
return label
}()
open var imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFit
imageView.tintColor = Color.Gray.P500
return imageView
}()
internal var isSelected: Bool = false {
didSet {
titleLabel.textColor = isSelected ? Color.Default.Text.Title : Color.Default.Tint.Inactive
imageView.tintColor = isSelected ? activeTint() : Color.Default.Tint.Inactive
imageView.image = isSelected ? (selectedImage?.withRenderingMode(.alwaysTemplate) ?? image) : image
}
}
fileprivate func activeTint() -> UIColor {
guard let bgColor = backgroundColor else {
return Color.Default.Tint.TabBar
}
return bgColor.isLight ? Color.Default.Tint.TabBar : Color.White
}
open weak var delegate: NTTabBarItemDelegate?
//MARK: - Initialization
public convenience init() {
self.init(frame: .zero)
}
convenience init(title: String?, image: UIImage?, selectedImage: UIImage?) {
self.init(frame: .zero)
}
public override init(frame: CGRect) {
super.init(frame: frame)
trackTouchLocation = false
ripplePercent = 0.8
touchUpAnimationTime = 0.5
tintColor = Color.Default.Tint.TabBar
backgroundColor = Color.Default.Background.TabBar
addSubview(imageView)
addSubview(titleLabel)
imageView.anchor(topAnchor, left: leftAnchor, bottom: titleLabel.topAnchor, right: rightAnchor, topConstant: 3, leftConstant: 5, bottomConstant: 5, rightConstant: 5, widthConstant: 0, heightConstant: 0)
titleLabel.anchor(nil, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 5, leftConstant: 0, bottomConstant: 3, rightConstant: 0, widthConstant: 0, heightConstant: 10)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override var tintColor: UIColor! {
get {
return super.tintColor
}
set {
super.tintColor = newValue
rippleColor = newValue.withAlpha(0.4)
}
}
open override var backgroundColor: UIColor? {
get {
return super.backgroundColor
}
set {
super.backgroundColor = newValue
}
}
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
delegate?.tabBarItem(didSelect: self)
isSelected = true
}
}
|
mit
|
a10f545b023d59462a1279ea56b4efca
| 32.835714 | 210 | 0.645345 | 4.78002 | false | false | false | false |
texuf/outandabout
|
outandabout/outandabout/RSBarcodes/RSExtendedCode39Generator.swift
|
4
|
4794
|
//
// RSExtendedCode39Generator.swift
// RSBarcodesSample
//
// Created by R0CKSTAR on 6/11/14.
// Copyright (c) 2014 P.D.Q. All rights reserved.
//
import UIKit
public let RSBarcodesTypeExtendedCode39Code = "com.pdq.rsbarcodes.code39.ext"
// http://www.barcodesymbols.com/code39.htm
// http://www.barcodeisland.com/code39.phtml
public class RSExtendedCode39Generator: RSCode39Generator {
func encodeContents(contents: String) -> String {
var encodedContents = ""
for character in contents {
let characterString = String(character)
switch characterString {
case "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z":
encodedContents += "+" + characterString.uppercaseString
case "!":
encodedContents += "/A"
case "\"":
encodedContents += "/B"
case "#":
encodedContents += "/C"
case "$":
encodedContents += "/D"
case "%":
encodedContents += "/E"
case "&":
encodedContents += "/F"
case "'":
encodedContents += "/G"
case "(":
encodedContents += "/H"
case ")":
encodedContents += "/I"
case "*":
encodedContents += "/J"
case "+":
encodedContents += "/K"
case ",":
encodedContents += "/L"
// - -> /M better to use -
// . -> /N better to use .
case "/":
encodedContents += "/O"
// 0 -> /P better to use 0
// 1 -> /Q better to use 1
// 2 -> /R better to use 2
// 3 -> /S better to use 3
// 4 -> /T better to use 4
// 5 -> /U better to use 5
// 6 -> /V better to use 6
// 7 -> /W better to use 7
// 8 -> /X better to use 8
// 9 -> /Y better to use 9
case ":":
encodedContents += "/Z"
// ESC -> %A
// FS -> %B
// GS -> %C
// RS -> %D
// US -> %E
case ";":
encodedContents += "%F"
case "<":
encodedContents += "%G"
case "=":
encodedContents += "%H"
case ">":
encodedContents += "%I"
case "?":
encodedContents += "%J"
case "[":
encodedContents += "%K"
case "\\":
encodedContents += "%L"
case "]":
encodedContents += "%M"
case "^":
encodedContents += "%N"
case "_":
encodedContents += "%O"
case "{":
encodedContents += "%P"
case "|":
encodedContents += "%Q"
case "}":
encodedContents += "%R"
case "~":
encodedContents += "%S"
// DEL -> %T
// NUL -> %U
case "@":
encodedContents += "%V"
case "`":
encodedContents += "%W"
// SOH -> $A
// STX -> $B
// ETX -> $C
// EOT -> $D
// ENQ -> $E
// ACK -> $F
// BEL -> $G
// BS -> $H
case "\t":
encodedContents += "$I"
// LF -> $J
// VT -> $K
// FF -> $L
case "\n":
encodedContents += "$M"
// SO -> $N
// SI -> $O
// DLE -> $P
// DC1 -> $Q
// DC2 -> $R
// DC3 -> $S
// DC4 -> $T
// NAK -> $U
// SYN -> $V
// ETB -> $W
// CAN -> $X
// EM -> $Y
// SUB -> $Z
default:
encodedContents += characterString
}
}
return encodedContents
}
override public func isValid(contents: String) -> Bool {
return contents.length() > 0
}
override public func barcode(contents: String) -> String {
return super.barcode(self.encodeContents(contents))
}
}
|
mit
|
df1bbea86d1ba6245dc54ec37733113c
| 32.298611 | 146 | 0.341677 | 4.451253 | false | false | false | false |
ntnmrndn/R.swift
|
Sources/RswiftCore/Generators/ResourceFileStructGenerator.swift
|
2
|
3218
|
//
// ResourceFileStructGenerator.swift
// R.swift
//
// Created by Mathijs Kadijk on 10-12-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
struct ResourceFileStructGenerator: ExternalOnlyStructGenerator {
private let resourceFiles: [ResourceFile]
init(resourceFiles: [ResourceFile]) {
self.resourceFiles = resourceFiles
}
func generatedStruct(at externalAccessLevel: AccessLevel, prefix: SwiftIdentifier) -> Struct {
let structName: SwiftIdentifier = "file"
let qualifiedName = prefix + structName
let localized = resourceFiles.grouped(by: { $0.fullname })
let groupedLocalized = localized.grouped(bySwiftIdentifier: { $0.0 })
groupedLocalized.printWarningsForDuplicatesAndEmpties(source: "resource file", result: "file")
// For resource files, the contents of the different locales don't matter, so we just use the first one
let firstLocales = groupedLocalized.uniques.map { ($0.0, Array($0.1.prefix(1))) }
return Struct(
availables: [],
comments: ["This `\(qualifiedName)` struct is generated, and contains static references to \(firstLocales.count) files."],
accessModifier: externalAccessLevel,
type: Type(module: .host, name: structName),
implements: [],
typealiasses: [],
properties: firstLocales.flatMap { propertiesFromResourceFiles(resourceFiles: $0.1, at: externalAccessLevel) },
functions: firstLocales.flatMap { functionsFromResourceFiles(resourceFiles: $0.1, at: externalAccessLevel) },
structs: [],
classes: []
)
}
private func propertiesFromResourceFiles(resourceFiles: [ResourceFile], at externalAccessLevel: AccessLevel) -> [Let] {
return resourceFiles
.map {
return Let(
comments: ["Resource file `\($0.fullname)`."],
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: $0.fullname),
typeDefinition: .inferred(Type.FileResource),
value: "Rswift.FileResource(bundle: R.hostingBundle, name: \"\($0.filename)\", pathExtension: \"\($0.pathExtension)\")"
)
}
}
private func functionsFromResourceFiles(resourceFiles: [ResourceFile], at externalAccessLevel: AccessLevel) -> [Function] {
return resourceFiles
.flatMap { resourceFile -> [Function] in
let fullname = resourceFile.fullname
let filename = resourceFile.filename
let pathExtension = resourceFile.pathExtension
return [
Function(
availables: [],
comments: ["`bundle.url(forResource: \"\(filename)\", withExtension: \"\(pathExtension)\")`"],
accessModifier: externalAccessLevel,
isStatic: true,
name: SwiftIdentifier(name: fullname),
generics: nil,
parameters: [
Function.Parameter(name: "_", type: Type._Void, defaultValue: "()")
],
doesThrow: false,
returnType: Type._URL.asOptional(),
body: "let fileResource = R.file.\(SwiftIdentifier(name: fullname))\nreturn fileResource.bundle.url(forResource: fileResource)"
)
]
}
}
}
|
mit
|
8be45da1f30f0750e91cc668ac8083b2
| 36.858824 | 139 | 0.659416 | 4.711567 | false | false | false | false |
guille969/MGBottomSheet
|
MGBottomSheet/MGBottomSheet/AppearanceAttributes/MGBottomSheetAppearenceAttributes.swift
|
1
|
2017
|
//
// MGBottomSheetAppearanceAttributes.swift
// MGBottomSheetController
//
// Created by Guillermo García Rebolo on 23/1/17.
// Copyright © 2017 Guillermo Garcia Rebolo. All rights reserved.
//
import UIKit
public class MGBottomSheetAppearanceAttributes: NSObject {
/**
Variable to set the text font of the section actions
- Author:
Guillermo Garcia Rebolo
- Version:
1.0.3
*/
public var sectionFont = UIFont()
/**
Variable to set the text font of the actions
- Author:
Guillermo Garcia Rebolo
- Version:
1.0.3
*/
public var textFont = UIFont()
/**
Variable to set the text color of the section actions
- Author:
Guillermo Garcia Rebolo
- Version:
1.0.3
*/
public var sectionColor = UIColor()
/**
Variable to set the text color of the actions
- Author:
Guillermo Garcia Rebolo
- Version:
1.0.3
*/
public var textColor = UIColor()
/**
Variable to set the image tint of the actions
- Author:
Guillermo Garcia Rebolo
- Version:
1.0.3
*/
public var imageTint = UIColor()
/**
Class method for configure the initial appearance of the MGBottomSheet
- Author:
Guillermo Garcia Rebolo
- Version:
1.0.3
*/
public class func configureDefaultTextStyle() -> MGBottomSheetAppearanceAttributes {
let appearanceAttributes = MGBottomSheetAppearanceAttributes()
appearanceAttributes.sectionFont = UIFont.systemFont(ofSize: 16)
appearanceAttributes.textFont = UIFont.systemFont(ofSize: 14)
appearanceAttributes.sectionColor = UIColor.lightGray
appearanceAttributes.textColor = UIColor.black
appearanceAttributes.imageTint = UIColor.black
return appearanceAttributes
}
}
|
mit
|
c514a4b8ee723fe3be6eade226f636c9
| 19.773196 | 88 | 0.600993 | 4.92665 | false | false | false | false |
jingkecn/WatchWorker
|
src/ios/JSCore/Workers/WatchWorkerGlobalScope.swift
|
1
|
3443
|
//
// WatchWorkerGlobalScope.swift
// WTVJavaScriptCore
//
// Created by Jing KE on 29/07/16.
// Copyright © 2016 WizTiVi. All rights reserved.
//
import Foundation
import JavaScriptCore
import WatchConnectivity
class WatchWorkerGlobalScope: DedicatedWorkerGlobalScope, WCSessionDelegate {
var session: WCSession? = {
guard WCSession.isSupported() else { return nil }
return WCSession.defaultSession()
}()
override init() {
super.init()
self.session?.delegate = self
self.session?.activateSession()
self.addEventListener("watchconnected", listener: EventListener.create(withHandler: self.onWatchConnected))
}
}
extension WatchWorkerGlobalScope {
func dispatchWatchConnection(ports: Array<MessagePort>) {
let event = MessageEvent.create(self, type: "watchconnected", initDict: [ "ports": ports ])
self.dispatchEvent(event)
}
}
extension WatchWorkerGlobalScope {
func onWatchConnected(event: Event) {
print("==================== [\(self.className)] Start handling watch connected event ====================")
guard let event = event as? MessageEvent else { return }
print("1. message event = \(event.debugInfo)")
guard let jsEvent = event.thisJSValue else { return }
print("2. event = \(jsEvent), event.instance = \(jsEvent.objectForKeyedSubscript("instance"))")
guard let onwatchconnected = self.getJSValue(byKey: "onwatchconnected") where !onwatchconnected.isUndefined && !onwatchconnected.isNull else { return }
print("4. Invoking [onwatchconnected] handler with arguments: \(jsEvent.objectForKeyedSubscript("instance"))")
onwatchconnected.callWithArguments([jsEvent])
print("==================== [\(self.className)] End handling watch connected event ====================")
}
override func onMessage(event: Event) {
super.onMessage(event)
guard let event = event as? MessageEvent else { return }
self.sendMessage(event.data)
}
}
// MARK: ********** Basic interactive messaging **********
extension WatchWorkerGlobalScope {
var isReachable: Bool {
return self.session?.reachable ?? false
}
func sendMessage(message: String) {
guard let session = self.session /*where session.reachable*/ else { return }
session.sendMessage([PHONE_MESSAGE: message], replyHandler: nil, errorHandler: nil)
}
func session(session: WCSession, didReceiveMessage message: [String : AnyObject]) {
print("Receiving message without reply handler...")
if let messageBody = message[WATCH_MESSAGE] as? String {
print("Receiving a message from iPhone: \(messageBody)")
dispatch_async(dispatch_get_main_queue(), {
self.postMessage(messageBody)
})
} else {
print("Receiving an invalid message: \(message)")
}
}
}
extension WatchWorkerGlobalScope {
override class func runWorker(worker: AbstractWorker) {
super.runWorker(worker)
guard let worker = worker as? WatchWorker else { return }
guard let scope = worker.scope as? WatchWorkerGlobalScope else { return }
guard let port = scope.port else { return }
guard scope.isReachable else { return }
scope.dispatchWatchConnection([scope.port!])
}
}
|
mit
|
16ec3558bdfd555d1c0b801a8cb1dd20
| 34.132653 | 159 | 0.641488 | 4.708618 | false | false | false | false |
Sharelink/Bahamut
|
Bahamut/BahamutRFKit/File/BahamutFire.swift
|
1
|
4029
|
//
// BahamutFire.swift
// Bahamut
//
// Created by AlexChow on 15/11/25.
// Copyright © 2015年 GStudio. All rights reserved.
//
import Foundation
import Alamofire
class BahamutFireClient : BahamutRFClient
{
init(fileApiServer:String,userId:String,token:String)
{
super.init(apiServer: fileApiServer, userId: userId, token: token)
}
override func setReqHeader(_ req: BahamutRFRequestBase) -> BahamutRFRequestBase
{
req.headers.updateValue(BahamutRFKit.appkey, forKey: "appkey")
return super.setReqHeader(req)
}
}
private let BahamutFireClientType = "BahamutFireClientType"
extension BahamutRFKit{
var fileApiServer:String!{
get{
return userInfos["fileApiServer"] as? String
}
set{
userInfos["fileApiServer"] = newValue
}
}
@discardableResult
func reuseFileApiServer(_ userId:String, token:String,fileApiServer:String) -> ClientProtocal
{
self.fileApiServer = fileApiServer
let fileClient = BahamutFireClient(fileApiServer:self.fileApiServer,userId:userId,token:token)
return useClient(fileClient, clientKey: BahamutFireClientType)
}
func getBahamutFireClient() -> BahamutFireClient
{
return clients[BahamutFireClientType] as! BahamutFireClient
}
}
//MARK: Bahamut Fire Bucket Extension
extension BahamutFireClient{
func sendFile(_ sendFileKey:FileAccessInfo,filePath:String)->UploadRequest
{
return sendFile(sendFileKey, filePathUrl: URL(fileURLWithPath: filePath))
}
func sendFile(_ sendFileKey:FileAccessInfo,filePathUrl:URL)->UploadRequest
{
let headers:HTTPHeaders = ["userId":self.userId,"token":self.token,"accessKey":sendFileKey.accessKey,"appkey":BahamutRFKit.appkey]
return Alamofire.upload(filePathUrl, to: sendFileKey.server, method: .post, headers: headers)
}
func sendFile(_ sendFileKey:FileAccessInfo,fileData:Data)->UploadRequest
{
let headers :HTTPHeaders = ["userId":self.userId,"token":self.token,"accessKey":sendFileKey.accessKey,"appkey":BahamutRFKit.appkey]
return Alamofire.upload(fileData, to: sendFileKey.server, method: .post, headers: headers)
}
func downloadFile(_ fileId:String,filePath:String) -> DownloadRequest
{
let headers :HTTPHeaders = ["userId":self.userId,"token":self.token,"appkey":BahamutRFKit.appkey]
let fileUrl = "\(self.apiServer)/Files/\(fileId)"
return Alamofire.download(fileUrl, method: .get, parameters: nil, encoding: URLEncoding.default, headers: headers) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
return (URL(fileURLWithPath: filePath),DownloadRequest.DownloadOptions.removePreviousFile)
}
}
}
/*
Get /BahamutFires/{fileId} : get a file request key for upload task
*/
open class GetBahamutFireRequest : BahamutRFRequestBase
{
public override init()
{
super.init()
self.api = "/BahamutFires"
self.method = .get
}
open var fileId:String!{
didSet{
self.api = "/BahamutFires/\(fileId!)"
}
}
open override func getMaxRequestCount() -> Int32 {
return BahamutRFRequestBase.maxRequestNoLimitCount
}
}
/*
POST /Files (fileType,fileSize) : get a new send file key for upload task
*/
open class NewBahamutFireRequest : BahamutRFRequestBase
{
public override init()
{
super.init()
self.api = "/BahamutFires"
self.method = .post
}
open var fileType:FileType! = .noType{
didSet{
self.paramenters["fileType"] = "\(fileType.rawValue)"
}
}
open var fileSize:Int = 512 * 1024{ //byte
didSet{
self.paramenters["fileSize"] = "\(fileSize)"
}
}
open override func getMaxRequestCount() -> Int32 {
return BahamutRFRequestBase.maxRequestNoLimitCount
}
}
|
mit
|
7cdcee7ba674a13797742318b750d365
| 29.270677 | 210 | 0.665425 | 4.347732 | false | false | false | false |
dunkelstern/FastString
|
src/faststring.swift
|
1
|
8801
|
// Copyright (c) 2016 Johannes Schriewer.
//
// 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.
// Always UTF-8
public class FastString {
internal var buffer: UnsafeMutableBufferPointer<UInt8>
public init() {
let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: 1)
memory[0] = 0
self.buffer = UnsafeMutableBufferPointer(start: memory, count: 0)
}
internal init(capacity: Int) {
let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: capacity + 1)
memory[capacity] = 0
self.buffer = UnsafeMutableBufferPointer(start: memory, count: capacity)
}
public init(_ string: String) {
// FIXME: use utf16 on osx
let count = string.utf8.count
let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: count + 1)
var index = 0
for c in string.utf8 {
memory[index] = c
index += 1
}
memory[count] = 0
self.buffer = UnsafeMutableBufferPointer(start: memory, count: count)
}
public convenience init?(nullTerminatedCString: UnsafePointer<Int8>) {
if let s = String(validatingUTF8: nullTerminatedCString) {
self.init(s)
return
}
return nil
}
public init(array: [Int8]) {
let count = array.count
let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: count + 1)
var index = 0
for c in array {
memory[index] = UInt8(bitPattern: c)
index += 1
}
memory[count] = 0
self.buffer = UnsafeMutableBufferPointer(start: memory, count: count)
}
public init(array: [UInt8]) {
let count = array.count
let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: count + 1)
var index = 0
for c in array {
memory[index] = c
index += 1
}
memory[count] = 0
self.buffer = UnsafeMutableBufferPointer(start: memory, count: count)
}
public init(buffer: UnsafeBufferPointer<UInt8>) {
let count = buffer.count
let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: count + 1)
var index = 0
for c in buffer {
memory[index] = c
index += 1
}
memory[count] = 0
self.buffer = UnsafeMutableBufferPointer(start: memory, count: count)
}
internal init(slice: MutableRandomAccessSlice<UnsafeMutableBufferPointer<UInt8>>) {
let count = slice.count
let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: count + 1)
var index = slice.startIndex
for c in slice {
memory[index] = c
index = slice.index(index, offsetBy: 1)
}
memory[count] = 0
self.buffer = UnsafeMutableBufferPointer(start: memory, count: count)
}
public init(fastString: FastString) {
let count = fastString.buffer.count
let memory = UnsafeMutablePointer<UInt8>(allocatingCapacity: count + 1)
var index = 0
for c in fastString.buffer {
memory[index] = c
index += 1
}
memory[count] = 0
self.buffer = UnsafeMutableBufferPointer(start: memory, count: count)
}
deinit {
self.buffer.baseAddress!.deallocateCapacity(self.buffer.count + 1)
}
public func toString() -> String? {
if let result = String(validatingUTF8: UnsafePointer<CChar>(self.buffer.baseAddress!)) {
return result
}
return nil
}
public func toArray() -> [UInt8] {
return [UInt8](self.buffer)
}
public var byteCount: Int {
return self.buffer.count
}
public var characterCount: Int {
// TODO: cache last result
var result: Int = 9
for _ in self.makeCharacterIterator(replaceInvalid: "?") {
result += 1
}
return result
}
public func makeByteIterator() -> AnyIterator<UInt8> {
var position = 0
return AnyIterator {
if position < self.buffer.count {
let result = self.buffer[position]
position += 1
return result
}
return nil
}
}
public subscript(_ index: Int) -> UInt8? {
if index < self.buffer.count {
return self.buffer[index]
}
return nil
}
public func makeCharacterIterator(replaceInvalid: Character? = nil) -> AnyIterator<Character> {
var position = 0
return AnyIterator {
if position < self.buffer.count {
// Check if we have an UTF8 sequence here
let c0 = self.buffer[position]
if c0 & 0x80 == 0 {
// ASCII character
position += 1
return Character(UnicodeScalar(c0))
} else if c0 & 0xe0 == 0xc0 {
// Sequence of two
if position + 1 < self.buffer.count {
let c1 = self.buffer[position + 1]
if c1 & 0xc0 == 0x80 {
// byte 2 is valid, combine
position += 2
var value = UInt16(c1 & 0x3f)
value += UInt16(c0 & 0x1f) << 6
return Character(UnicodeScalar(value))
}
}
} else if c0 & 0xf0 == 0xe0 {
// Sequence of three
if position + 2 < self.buffer.count {
let c1 = self.buffer[position + 1]
let c2 = self.buffer[position + 2]
if c1 & 0xc0 == 0x80 && c2 & 0xc0 == 0x80 {
// byte 2 and 3 are valid, combine
position += 3
var value = UInt32(c2 & 0x3f)
value += UInt32(c1 & 0x3f) << 6
value += UInt32(c0 & 0x1f) << 12
return Character(UnicodeScalar(value))
}
}
} else if c0 & 0xf8 == 0xf0 {
// Sequence of four
if position + 3 < self.buffer.count {
let c1 = self.buffer[position + 1]
let c2 = self.buffer[position + 2]
let c3 = self.buffer[position + 3]
if c1 & 0xc0 == 0x80 && c2 & 0xc0 == 0x80 && c3 & 0xc0 == 0x80 {
// byte 2, 3 and 4 are valid, combine
position += 4
var value = UInt32(c3 & 0x3f)
value += UInt32(c2 & 0x3f) << 6
value += UInt32(c1 & 0x3f) << 12
value += UInt32(c0 & 0x1f) << 18
return Character(UnicodeScalar(value))
}
}
}
// Invalid
if let replacement = replaceInvalid {
return replacement
}
return nil // this ends the iterator
}
return nil
}
}
}
extension FastString: CustomStringConvertible {
public var description: String {
return String(validatingUTF8: UnsafePointer<CChar>(self.buffer.baseAddress!)) ?? "<UTF8-Conversion error>"
}
}
extension FastString: Hashable {
public var hashValue: Int {
return self.buffer.baseAddress!.hashValue
}
}
public func ==(lhs: FastString, rhs: FastString) -> Bool {
if lhs.byteCount != rhs.byteCount {
return false
}
for i in 0..<lhs.byteCount {
if lhs.buffer[i] != rhs.buffer[i] {
return false
}
}
return true
}
public func ==(lhs: FastString, rhs: String) -> Bool {
if lhs.byteCount != rhs.utf8.count {
return false
}
var index = rhs.utf8.startIndex
for i in 0..<lhs.byteCount {
if lhs.buffer[i] != rhs.utf8[index] {
return false
}
index = rhs.utf8.index(index, offsetBy: 1)
}
return true
}
|
apache-2.0
|
584c38de379ae975f1d04e47f17bb162
| 32.591603 | 114 | 0.523577 | 4.644327 | false | false | false | false |
slepcat/mint
|
MINT/Mint.swift
|
1
|
25652
|
//
// Mint.swift
// MINT
//
// Created by NemuNeko on 2015/03/15.
// Copyright (c) 2015年 Taizo A. All rights reserved.
//
import Foundation
public class MintInterpreter : Interpreter, MintLeafSubject {
var observers:[MintLeafObserver] = []
weak var controller : MintController!
var autoupdate : Bool = true
override init() {
MintStdPort.get.setPort(newPort: Mint3DPort())
MintStdPort.get.setErrPort(MintErrPort())
MintStdPort.get.setReadPort(newPort: MintImportPort())
super.init()
}
// register observer (mint leaf view) protocol
func registerObserver(_ observer: MintLeafObserver) {
observers.append(observer)
let obs = lookup(observer.uid)
if let pair = obs.target as? Pair {
if let f = pair.car.eval(global) as? Form {
observer.init_opds(delayed_list_of_values(pair), labels: ["proc"] + f.params_str())
} else if let p = pair.car.eval(global) as? Procedure {
observer.init_opds(delayed_list_of_values(pair), labels: ["proc"] + p.params_str())
} else {
observer.init_opds(delayed_list_of_values(pair), labels: [])
}
observer.setName(pair.car.str("", level: 0))
} else {
print("unexpected error: leaf must be pair", terminator: "\n")
}
}
// remove observer
func removeObserver(_ observer: MintLeafObserver) {
for i in stride(from: 0, to: observers.count, by: 1) {
if observers[i] === observer {
observers.remove(at: i)
break
}
}
}
// update observer
func update(_ leafid: UInt, newopds:[SExpr], newuid: UInt, olduid: UInt) {
for obs in observers {
obs.update(leafid, newopds: newopds, newuid: newuid, olduid: olduid)
}
}
// lookup uid of s-expression which include designated uid object.
public func lookup_leaf_of(_ uid: UInt) -> UInt? {
for tree in trees {
if tree.uid == uid {
return uid
} else {
if let pair = tree as? Pair {
if let res = rec_lookup_leaf(uid, expr: pair) {
return res
}
}
}
}
return nil
}
public func rec_lookup_leaf(_ uid: UInt, expr: Pair) -> UInt? {
var unchecked : [Pair] = []
let chain = gen_pairchain_of_leaf(expr)
for pair in chain {
if pair.car.uid == uid {
return expr.uid
/*
if let pair2 = pair.car as? Pair {
return pair2.uid
} else {
return expr.uid
}
*/
} else if pair.cdr.uid == uid {
return expr.uid
} else {
if let pair2 = pair.car as? Pair {
unchecked.append(pair2)
}
}
}
while unchecked.count > 0 {
let head = unchecked.removeLast()
if let res = rec_lookup_leaf(uid, expr: head) {
return res
}
}
return nil
}
private func gen_pairchain_of_leaf(_ exp:SExpr) -> [Pair] {
var acc : [Pair] = []
var head = exp
while true {
if let pair = head as? Pair {
acc.append(pair)
head = pair.cdr
} else {
return acc
}
}
}
///// run around /////
public func run_around(_ uid : UInt) {
if autoupdate {
eval(uid)
}
}
///// Manipulating S-Expression /////
public func newSExpr(_ rawstr: String) -> UInt? {
// internal function to generate s-expression from a proc
func genSExp(_ proc: Form) -> Pair {
let head = Pair(car: proc)
var ct = head
let params = proc.params_str()
for p in params {
ct.cdr = Pair(car: MStr(_value: "<" + p + ">" ))
ct = ct.cdr as! Pair
}
return head
}
let expr = read(rawstr)
// add defined proc and primitives
if let s = expr as? MSymbol {
if let proc = s.eval(global) as? Procedure {
let list = genSExp(proc)
list.car = s
trees.append(list)
return list.uid
} else if let prim = s.eval(global) as? Primitive {
let list = genSExp(prim)
list.car = s
trees.append(list)
return list.uid
}
// add special forms
} else if let f = expr as? Form {
let list = genSExp(f)
trees.append(list)
return list.uid
// add empty parathentes
} else if let _ = expr as? MNull {
let emptylist = Pair()
trees.append(emptylist)
return emptylist.uid
}
return nil//failed to add exp
}
public func remove(_ uid: UInt) {
for i in stride(from:0, to: trees.count, by: 1) {
let res = trees[i].lookup_exp(uid)
if !res.target.isNull() {
let opds = delayed_list_of_values(res.target)
if res.conscell.isNull() {
trees.remove(at: i)
break
} else if let pair = res.conscell as? Pair {
if pair.car.uid == uid {
pair.car = MStr(_value: "<unlinked>")
if let leafid = lookup_leaf_of(pair.uid) {
update(leafid, newopds: [pair.car], newuid: pair.car.uid, olduid: res.target.uid)
}
} else {
print("unexpected err, failed to remove leaf")
}
} else {
print("fail to remove. bad conscell", terminator: "\n")
}
for exp in opds {
if let pair = exp as? Pair {
trees.append(pair)
}
}
//return res.target
}
}
//return MNull()
}
public func add_arg(_ uid: UInt, rawstr: String) -> UInt {
let res = lookup(uid)
if let pair = res.target as? Pair {
var head = pair
while !head.cdr.isNull() {
if let pair2 = head.cdr as? Pair {
head = pair2
}
}
head.cdr = Pair(car: read(rawstr + "\n"))
update(uid, newopds: [head.cadr], newuid: head.cadr.uid, olduid: 0)
print("arg (id: \(head.cadr.uid)) is added to leaf (id: \(uid))", terminator: "\n")
print_exps()
return head.cadr.uid
}
return 0
}
public func overwrite_arg(_ uid: UInt, leafid: UInt, rawstr: String) -> UInt {
let res = lookup(uid)
if let pair = res.conscell as? Pair {
pair.car = read(rawstr + "\n")
update(leafid, newopds: [pair.car], newuid: pair.car.uid, olduid: uid)
print("arg (id: \(uid)) of leaf (id: \(leafid)) is overwritten by the new arg (id: \(pair.car.uid))", terminator: "\n")
print_exps()
return pair.car.uid
}
return 0
}
public func link_toArg(_ ofleafid:UInt, uid: UInt, fromUid: UInt) {
let res = lookup(uid)
let rewrite = lookup(fromUid)
// if target leaf has been linked, unlink from member of tree.
if !rewrite.conscell.isNull() {
if let oldleafid = lookup_leaf_of(fromUid) {
unlink_arg(fromUid, ofleafid: oldleafid)
}
}
// remove from trees of interpreter
for i in stride(from: 0, to: trees.count, by: 1) {
if trees[i].uid == fromUid {
trees.remove(at: i)
print("leaf (id: \(fromUid)) removed from interpreter trees", terminator: "\n")
break
}
}
if let pair = res.conscell as? Pair {
// if old argument is Pair, append it to interpreter trees before overwrite.
if let removed = res.target as? Pair {
trees.append(removed)
print("leaf (id: \(removed.uid)) added to interpreter trees", terminator: "\n")
}
pair.car = rewrite.target
}
update(ofleafid, newopds: [rewrite.target], newuid: fromUid, olduid: uid)
print_exps()
}
public func unlink_arg(_ uid: UInt, ofleafid: UInt) {
let res = lookup(uid)
//if !res.target.isNull() {
// move to interpreter trees
trees.append(res.target)
print("leaf (id: \(res.target.uid)) added to interpreter trees", terminator: "\n")
//}
// remove from current tree
if let pair = res.conscell as? Pair {
pair.car = MStr(_value: "<unlinked>")
print("unlink old arg (id: \(uid)) in leaf (id: \(ofleafid))", terminator: "\n")
update(ofleafid, newopds: [pair.car], newuid: pair.car.uid, olduid: uid)
}
}
public func remove_arg(_ uid:UInt, ofleafid: UInt) {
let removedArg = lookup(uid)
let parent = lookup(removedArg.conscell.uid)
if let parentPair = parent.conscell as? Pair, let removedPair = removedArg.conscell as? Pair {
parentPair.cdr = removedPair.cdr
update(ofleafid, newopds: [], newuid: 0, olduid: uid)
} else {
print("error: unexpected remove of element", terminator: "\n")
}
}
public func set_ref(_ toArg:UInt, ofleafid:UInt, symbolUid: UInt) -> UInt?{
let def = lookup(symbolUid)
if let pair = def.target as? Pair {
if let symbol = pair.cadr as? MSymbol {
return overwrite_arg(toArg, leafid: ofleafid, rawstr: symbol.key)
} else if let symbol = pair.caadr as? MSymbol {
return overwrite_arg(toArg, leafid: ofleafid, rawstr: symbol.key)
} else {
print("error: unexpectedly symbol not found", terminator:"\n")
}
} else {
print("error: leaf is not define?", terminator: "\n")
}
return nil
}
public func move_arg(_ uid: UInt, toNextOfUid: UInt) {
let nextTo = lookup(toNextOfUid)
let moveArg = lookup(uid)
if let pair1 = nextTo.conscell as? Pair, let pair2 = moveArg.conscell as? Pair {
pair1.car = moveArg.target
pair2.car = nextTo.target
} else {
print("error: move element must move inside conscell.", terminator: "\n")
}
}
///// output /////
public func str_with_pos(_ _positions: [(uid: UInt, pos: NSPoint)]) -> String {
var positions = _positions
var acc : String = ""
for expr in trees {
acc += expr.str_with_pos(&positions, indent: indent, level: 1) + "\n\n"
}
return acc
}
///// read Env /////
public func isSymbol_as_global(_ exp:MSymbol) -> Bool {
if let _ = global.hash_table.index(forKey: exp.key) {
return true
} else if !autoupdate {
// if autoupdate is off, global table may not have the key yet
// return true. because true mean reset all ref links in MintCommand
return true
} else {
return false
}
}
public func isSymbol_as_proc(_ exp: MSymbol) -> Bool {
if let _ = global.hash_table[exp.key] as? Procedure {
return true
} else {
if let i = lookup_treeindex_of(exp.uid) {
let path = rec_root2leaf_path(exp.uid, exps: trees[i])
for elem in path {
if let pair = elem as? Pair {
if let _ = pair.car as? MDefine, let sym = pair.cadr as? MSymbol {
if sym.key == exp.key {
return true
}
}
}
}
}
}
return false
}
/*
public func who_define(key: String) -> UInt {
for t in trees {
if let pair = t as? Pair {
if let _ = pair.car as? MDefine {
if let symbol = pair.cadr as? MSymbol {
if symbol.key == key {
return pair.uid
}
} else if let symbol = pair.caadr as? MSymbol {
if symbol.key == key {
return 0//pair.uid //proc is not take ref link
}
}
}
}
}
return 0
}*/
/// check if designated symbol is declaration of define variable or define itself
public func isDeclaration_of_var(_ exp: SExpr) -> Bool {
if let i = lookup_treeindex_of(exp.uid) {
let path = rec_root2leaf_path(exp.uid, exps: trees[i]) // <- macro expansion : todo
for elem in path {
if let pair = elem as? Pair {
switch pair.car {
case _ as MDefine:
// uid is define var
if pair.cadr.uid == exp.uid {
return true
// uid is element of defined var list
} else if let paramPair = pair.cadr as? Pair {
let syms = delayed_list_of_values(paramPair.cdr)
for sym in syms {
if sym.uid == exp.uid {
return true
}
}
}
case _ as MLambda:
let syms = delayed_list_of_values(pair.cadr)
for sym in syms {
if sym.uid == exp.uid {
return true
}
}
default:
break
}
}
}
}
return false
}
// check if designated uid is define or lambda
public func isDefine(_ exp: SExpr) -> Bool {
// todo: macro expansion
switch exp {
case _ as MDefine:
return true
case _ as MLambda:
return true
default:
return false
}
}
/// check if designated exp is display
public func isDisplay(_ exp: SExpr) -> Bool {
// todo : macro expansion
if let _ = exp as? Display {
return true
} else {
return false
}
}
/// search interpreter trees to get node who define designated symbol
public func who_define(_ exp:MSymbol) -> UInt? {
if isSymbol_as_proc(exp) {
return nil
}
// search from bottom of binary tree
// to applicable for lexical scope
// ::: todo> macro applicable
if let i = lookup_treeindex_of(exp.uid) {
let path = rec_root2leaf_path(exp.uid, exps: trees[i])// <- macro expansion point :todo
for elem in path {
if let pair = elem as? Pair {
switch pair.car {
case _ as MDefine:
if let param = pair.cadr as? MSymbol {
if (param.uid != exp.uid) && (param.key == exp.key) {
return lookup_leaf_of(param.uid)
}
} else if let paramPair = pair.cadr as? Pair {
let syms = delayed_list_of_values(paramPair.cdr)
for sym in syms {
if let symbol = sym as? MSymbol {
if (symbol.uid != exp.uid) && (symbol.key == exp.key) {
return lookup_leaf_of(symbol.uid)
// if designated symbol is declaration of define, return nil
} else if (symbol.uid == exp.uid) && (symbol.key == exp.key) {
return nil
}
}
}
}
case _ as MLambda:
let syms = delayed_list_of_values(pair.cadr)
for sym in syms {
if let symbol = sym as? MSymbol {
if (symbol.uid != exp.uid) && (symbol.key == exp.key) {
return lookup_leaf_of(symbol.uid)
}
}
}
default:
break
}
}
}
// if local define is not found, search top level
for j in stride(from: 0, to: trees.count ,by: 1) {
// skip already searched tree
if i == j { continue }
// check if this tree has the symbol
let resid = rec_search_symbol(exp.key, tree: trees[j])
if resid > 0 {
// search from root to bottom
let path2 = rec_root2leaf_path(resid, exps: trees[j]).reversed() //<- macro expantion point : todo
for elem in path2 {
if let pair = elem as? Pair {
if let _ = pair.car as? MDefine, let param = pair.cadr as? MSymbol {
if (param.uid != exp.uid) && (param.key == exp.key) {
return lookup_leaf_of(param.uid)
}
} else if let _ = pair.car as? MLambda {
break
}
}
}
}
}
}
return nil
}
// get chain of exps from target exp to tree root exp
private func rec_root2leaf_path(_ uid:UInt, exps:SExpr) -> [SExpr] {
if let atom = exps as? Atom {
if atom.uid == uid {
return [atom]
} else {
return []
}
} else {
if let pair = exps as? Pair {
if pair.uid == uid {
return [pair]
} else {
var ret : [SExpr] = []
let resl = rec_root2leaf_path(uid, exps: pair.car)
if resl.count > 0 {
ret = resl + [pair]
}
let resr = rec_root2leaf_path(uid, exps: pair.cdr)
if resr.count > 0 {
ret = resr + [pair]
}
return ret
}
}
}
return []
}
private func rec_search_symbol(_ key: String, tree: SExpr) -> UInt {
if let atom = tree as? Atom {
if let sym = atom as? MSymbol {
if sym.key == key {
return sym.uid
}
}
} else if let pair = tree as? Pair {
return rec_search_symbol(key, tree: pair.car) + rec_search_symbol(key, tree: pair.cdr)
}
return 0
}
func collect_symbols() -> [MSymbol] {
var acc :[MSymbol] = []
for tree in trees {
acc += rec_collect_symbols(tree)
}
return acc
}
private func rec_collect_symbols(_ tree: SExpr) -> [MSymbol] {
if let sym = tree as? MSymbol {
if !isSymbol_as_proc(sym) {
return [sym]
}
} else if let pair = tree as? Pair {
return rec_collect_symbols(pair.car) + rec_collect_symbols(pair.cdr)
}
return []
}
public func defined_exps() -> [String : [String]] {
var acc : [String : [String]] = [:]
for defined in global.hash_table {
if let proc = defined.1 as? Procedure {
if let list = acc[proc.category] {
acc[proc.category] = list + [defined.0]
} else {
acc[proc.category] = [defined.0]
}
} else if let form = defined.1 as? Form {
if let list = acc[form.category] {
acc[form.category] = list + [defined.0]
} else {
acc[form.category] = [defined.0]
}
}
}
if let leaves = acc["3D Primitives"] {
acc["3D Primitives"] = leaves + ["display"]
} else {
acc["3D Primitives"] = ["display"]
}
acc["lisp special form"] = ["define", "set!", "if", "quote", "lambda", "begin", "null"]
return acc
}
///// debugging /////
func print_exps() {
for tree in trees {
//print(tree._debug_string(),terminator: "\n")
print(tree.str(" ", level: 1),terminator: "\n")
}
}
}
extension SExpr {
func str_with_pos(_ positions: inout [(uid: UInt, pos: NSPoint)], indent: String, level: Int) -> String {
if let _ = self as? Pair {
var leveledIndent : String = ""
for _ in stride(from: 0, to: level, by: 1) {
leveledIndent += indent
}
let res = str_pos_list_of_exprs(self, positions: &positions, indent: indent, level: level + 1 )
var acc : String = ""
var pos : String = "("
for i in stride(from: 0, to: positions.count, by: 1) {
if self.uid == positions[i].uid {
pos += "_pos_ \(positions[i].pos.x) \(positions[i].pos.y) "
positions.remove(at: i)
break
}
}
for s in res {
if s[s.startIndex] == "(" {
if indent == "" {
acc += s
} else {
acc += "\n" + leveledIndent + s
}
} else {
if acc == "" {
acc += s
} else {
acc += " " + s
}
}
}
return pos + "(" + acc + "))"
} else {
return self.str(indent, level: level)
}
}
private func str_pos_list_of_exprs(_ _opds :SExpr, positions: inout [(uid: UInt, pos: NSPoint)], indent:String, level: Int) -> [String] {
if let atom = _opds as? Atom {
return [atom.str(indent, level: level)]
} else {
return tail_str_pos_list_of_exprs(_opds, acc: [], positions: &positions, indent: indent, level: level)
}
}
private func tail_str_pos_list_of_exprs(_ _opds :SExpr, acc: [String], positions: inout [(uid: UInt, pos: NSPoint)], indent:String, level: Int) -> [String] {
var acc2 = acc
if let pair = _opds as? Pair {
acc2.append(pair.car.str_with_pos(&positions, indent: indent, level: level))
return tail_str_pos_list_of_exprs(pair.cdr, acc: acc2, positions: &positions, indent: indent, level: level)
} else {
return acc
}
}
}
|
gpl-3.0
|
618a6d26efab7ef61727fb4536345464
| 31.969152 | 161 | 0.418129 | 4.639175 | false | false | false | false |
johnno1962b/swift-corelibs-foundation
|
Foundation/FileManager.swift
|
1
|
61076
|
// 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(OSX) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
#if os(Android) // struct stat.st_mode is UInt32
internal func &(left: UInt32, right: mode_t) -> mode_t {
return mode_t(left) & right
}
#endif
import CoreFoundation
open class FileManager : NSObject {
/* Returns the default singleton instance.
*/
private static let _default = FileManager()
open class var `default`: FileManager {
get {
return _default
}
}
/* Returns an NSArray of NSURLs locating the mounted volumes available on the computer. The property keys that can be requested are available in NSURL.
*/
open func mountedVolumeURLs(includingResourceValuesForKeys propertyKeys: [URLResourceKey]?, options: VolumeEnumerationOptions = []) -> [URL]? {
NSUnimplemented()
}
/* Returns an NSArray of NSURLs identifying the the directory entries.
If the directory contains no entries, this method will return the empty array. When an array is specified for the 'keys' parameter, the specified property values will be pre-fetched and cached with each enumerated URL.
This method always does a shallow enumeration of the specified directory (i.e. it always acts as if NSDirectoryEnumerationSkipsSubdirectoryDescendants has been specified). If you need to perform a deep enumeration, use -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:].
If you wish to only receive the URLs and no other attributes, then pass '0' for 'options' and an empty NSArray ('[NSArray array]') for 'keys'. If you wish to have the property caches of the vended URLs pre-populated with a default set of attributes, then pass '0' for 'options' and 'nil' for 'keys'.
*/
open func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: DirectoryEnumerationOptions = []) throws -> [URL] {
var error : Error? = nil
let e = self.enumerator(at: url, includingPropertiesForKeys: keys, options: mask.union(.skipsSubdirectoryDescendants)) { (url, err) -> Bool in
error = err
return false
}
var result = [URL]()
if let e = e {
for url in e {
result.append(url as! URL)
}
if let error = error {
throw error
}
}
return result
}
/* -URLsForDirectory:inDomains: is analogous to NSSearchPathForDirectoriesInDomains(), but returns an array of NSURL instances for use with URL-taking APIs. This API is suitable when you need to search for a file or files which may live in one of a variety of locations in the domains specified.
*/
open func urls(for directory: SearchPathDirectory, in domainMask: SearchPathDomainMask) -> [URL] {
NSUnimplemented()
}
/* -URLForDirectory:inDomain:appropriateForURL:create:error: is a URL-based replacement for FSFindFolder(). It allows for the specification and (optional) creation of a specific directory for a particular purpose (e.g. the replacement of a particular item on disk, or a particular Library directory.
You may pass only one of the values from the NSSearchPathDomainMask enumeration, and you may not pass NSAllDomainsMask.
*/
open func url(for directory: SearchPathDirectory, in domain: SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool) throws -> URL {
NSUnimplemented()
}
/* Sets 'outRelationship' to NSURLRelationshipContains if the directory at 'directoryURL' directly or indirectly contains the item at 'otherURL', meaning 'directoryURL' is found while enumerating parent URLs starting from 'otherURL'. Sets 'outRelationship' to NSURLRelationshipSame if 'directoryURL' and 'otherURL' locate the same item, meaning they have the same NSURLFileResourceIdentifierKey value. If 'directoryURL' is not a directory, or does not contain 'otherURL' and they do not locate the same file, then sets 'outRelationship' to NSURLRelationshipOther. If an error occurs, returns NO and sets 'error'.
*/
open func getRelationship(_ outRelationship: UnsafeMutablePointer<URLRelationship>, ofDirectoryAt directoryURL: URL, toItemAt otherURL: URL) throws {
NSUnimplemented()
}
/* Similar to -[NSFileManager getRelationship:ofDirectoryAtURL:toItemAtURL:error:], except that the directory is instead defined by an NSSearchPathDirectory and NSSearchPathDomainMask. Pass 0 for domainMask to instruct the method to automatically choose the domain appropriate for 'url'. For example, to discover if a file is contained by a Trash directory, call [fileManager getRelationship:&result ofDirectory:NSTrashDirectory inDomain:0 toItemAtURL:url error:&error].
*/
open func getRelationship(_ outRelationship: UnsafeMutablePointer<URLRelationship>, of directory: SearchPathDirectory, in domainMask: SearchPathDomainMask, toItemAt url: URL) throws {
NSUnimplemented()
}
/* createDirectoryAtURL:withIntermediateDirectories:attributes:error: creates a directory at the specified URL. If you pass 'NO' for withIntermediateDirectories, the directory must not exist at the time this call is made. Passing 'YES' for withIntermediateDirectories will create any necessary intermediate directories. This method returns YES if all directories specified in 'url' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference.
*/
open func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws {
guard url.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url])
}
try self.createDirectory(atPath: url.path, withIntermediateDirectories: createIntermediates, attributes: attributes)
}
/* createSymbolicLinkAtURL:withDestinationURL:error: returns YES if the symbolic link that point at 'destURL' was able to be created at the location specified by 'url'. 'destURL' is always resolved against its base URL, if it has one. If 'destURL' has no base URL and it's 'relativePath' is indeed a relative path, then a relative symlink will be created. If this method returns NO, the link was unable to be created and an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
*/
open func createSymbolicLink(at url: URL, withDestinationURL destURL: URL) throws {
guard url.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url])
}
guard destURL.scheme == nil || destURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : destURL])
}
try self.createSymbolicLink(atPath: url.path, withDestinationPath: destURL.path)
}
/* Instances of FileManager may now have delegates. Each instance has one delegate, and the delegate is not retained. In versions of Mac OS X prior to 10.5, the behavior of calling [[NSFileManager alloc] init] was undefined. In Mac OS X 10.5 "Leopard" and later, calling [[NSFileManager alloc] init] returns a new instance of an FileManager.
*/
open weak var delegate: FileManagerDelegate? {
NSUnimplemented()
}
/* setAttributes:ofItemAtPath:error: returns YES when the attributes specified in the 'attributes' dictionary are set successfully on the item specified by 'path'. If this method returns NO, a presentable NSError will be provided by-reference in the 'error' parameter. If no error is required, you may pass 'nil' for the error.
This method replaces changeFileAttributes:atPath:.
*/
open func setAttributes(_ attributes: [FileAttributeKey : Any], ofItemAtPath path: String) throws {
for attribute in attributes.keys {
if attribute == .posixPermissions {
guard let number = attributes[attribute] as? NSNumber else {
fatalError("Can't set file permissions to \(attributes[attribute] as Any?)")
}
#if os(OSX) || os(iOS)
let modeT = number.uint16Value
#elseif os(Linux) || os(Android) || CYGWIN
let modeT = number.uint32Value
#endif
if chmod(path, mode_t(modeT)) != 0 {
fatalError("errno \(errno)")
}
} else {
fatalError("Attribute type not implemented: \(attribute)")
}
}
}
/* createDirectoryAtPath:withIntermediateDirectories:attributes:error: creates a directory at the specified path. If you pass 'NO' for createIntermediates, the directory must not exist at the time this call is made. Passing 'YES' for 'createIntermediates' will create any necessary intermediate directories. This method returns YES if all directories specified in 'path' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference.
This method replaces createDirectoryAtPath:attributes:
*/
open func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws {
if createIntermediates {
var isDir: ObjCBool = false
if !fileExists(atPath: path, isDirectory: &isDir) {
let parent = path._nsObject.deletingLastPathComponent
if !fileExists(atPath: parent, isDirectory: &isDir) {
try createDirectory(atPath: parent, withIntermediateDirectories: true, attributes: attributes)
}
if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0 {
throw _NSErrorWithErrno(errno, reading: false, path: path)
} else if let attr = attributes {
try self.setAttributes(attr, ofItemAtPath: path)
}
} else if isDir.boolValue {
return
} else {
throw _NSErrorWithErrno(EEXIST, reading: false, path: path)
}
} else {
if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0 {
throw _NSErrorWithErrno(errno, reading: false, path: path)
} else if let attr = attributes {
try self.setAttributes(attr, ofItemAtPath: path)
}
}
}
/**
Performs a shallow search of the specified directory and returns the paths of any contained items.
This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”) but it does return other hidden files (files that begin with a period character).
The order of the files in the returned array is undefined.
- Parameter path: The path to the directory whose contents you want to enumerate.
- Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code.
- Returns: An array of String each of which identifies a file, directory, or symbolic link contained in `path`. The order of the files returned is undefined.
*/
open func contentsOfDirectory(atPath path: String) throws -> [String] {
var contents : [String] = [String]()
let dir = opendir(path)
if dir == nil {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue, userInfo: [NSFilePathErrorKey: path])
}
defer {
closedir(dir!)
}
while let entry = readdir(dir!) {
let entryName = withUnsafePointer(to: &entry.pointee.d_name) {
String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self))
}
// TODO: `entryName` should be limited in length to `entry.memory.d_namlen`.
if entryName != "." && entryName != ".." {
contents.append(entryName)
}
}
return contents
}
/**
Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories.
This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion.
Because this method recurses the directory’s contents, you might not want to use it in performance-critical code. Instead, consider using the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: or enumeratorAtPath: method to enumerate the directory contents yourself. Doing so gives you more control over the retrieval of items and more opportunities to abort the enumeration or perform other tasks at the same time.
- Parameter path: The path of the directory to list.
- Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code.
- Returns: An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file.
*/
open func subpathsOfDirectory(atPath path: String) throws -> [String] {
var contents : [String] = [String]()
let dir = opendir(path)
if dir == nil {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue, userInfo: [NSFilePathErrorKey: path])
}
defer {
closedir(dir!)
}
var entry = readdir(dir!)
while entry != nil {
let entryName = withUnsafePointer(to: &entry!.pointee.d_name) {
String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self))
}
// TODO: `entryName` should be limited in length to `entry.memory.d_namlen`.
if entryName != "." && entryName != ".." {
contents.append(entryName)
let entryType = withUnsafePointer(to: &entry!.pointee.d_type) { (ptr) -> Int32 in
return Int32(ptr.pointee)
}
#if os(OSX) || os(iOS)
let tempEntryType = entryType
#elseif os(Linux) || os(Android) || CYGWIN
let tempEntryType = Int32(entryType)
#endif
if tempEntryType == Int32(DT_DIR) {
let subPath: String = path + "/" + entryName
let entries = try subpathsOfDirectory(atPath: subPath)
contents.append(contentsOf: entries.map({file in "\(entryName)/\(file)"}))
}
}
entry = readdir(dir!)
}
return contents
}
/* attributesOfItemAtPath:error: returns an NSDictionary of key/value pairs containing the attributes of the item (file, directory, symlink, etc.) at the path in question. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
This method replaces fileAttributesAtPath:traverseLink:.
*/
open func attributesOfItem(atPath path: String) throws -> [FileAttributeKey : Any] {
var s = stat()
guard lstat(path, &s) == 0 else {
throw _NSErrorWithErrno(errno, reading: true, path: path)
}
var result = [FileAttributeKey : Any]()
result[.size] = NSNumber(value: UInt64(s.st_size))
#if os(OSX) || os(iOS)
let ti = (TimeInterval(s.st_mtimespec.tv_sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtimespec.tv_nsec))
#elseif os(Android)
let ti = (TimeInterval(s.st_mtime) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtime_nsec))
#else
let ti = (TimeInterval(s.st_mtim.tv_sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtim.tv_nsec))
#endif
result[.modificationDate] = Date(timeIntervalSinceReferenceDate: ti)
result[.posixPermissions] = NSNumber(value: UInt64(s.st_mode & 0o7777))
result[.referenceCount] = NSNumber(value: UInt64(s.st_nlink))
result[.systemNumber] = NSNumber(value: UInt64(s.st_dev))
result[.systemFileNumber] = NSNumber(value: UInt64(s.st_ino))
let pwd = getpwuid(s.st_uid)
if pwd != nil && pwd!.pointee.pw_name != nil {
let name = String(cString: pwd!.pointee.pw_name)
result[.ownerAccountName] = name
}
let grd = getgrgid(s.st_gid)
if grd != nil && grd!.pointee.gr_name != nil {
let name = String(cString: grd!.pointee.gr_name)
result[.groupOwnerAccountName] = name
}
var type : FileAttributeType
switch s.st_mode & S_IFMT {
case S_IFCHR: type = .typeCharacterSpecial
case S_IFDIR: type = .typeDirectory
case S_IFBLK: type = .typeBlockSpecial
case S_IFREG: type = .typeRegular
case S_IFLNK: type = .typeSymbolicLink
case S_IFSOCK: type = .typeSocket
default: type = .typeUnknown
}
result[.type] = type
if type == .typeBlockSpecial || type == .typeCharacterSpecial {
result[.deviceIdentifier] = NSNumber(value: UInt64(s.st_rdev))
}
#if os(OSX) || os(iOS)
if (s.st_flags & UInt32(UF_IMMUTABLE | SF_IMMUTABLE)) != 0 {
result[.immutable] = NSNumber(value: true)
}
if (s.st_flags & UInt32(UF_APPEND | SF_APPEND)) != 0 {
result[.appendOnly] = NSNumber(value: true)
}
#endif
result[.ownerAccountID] = NSNumber(value: UInt64(s.st_uid))
result[.groupOwnerAccountID] = NSNumber(value: UInt64(s.st_gid))
return result
}
#if !os(Android)
/* attributesOfFileSystemForPath:error: returns an NSDictionary of key/value pairs containing the attributes of the filesystem containing the provided path. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
This method replaces fileSystemAttributesAtPath:.
*/
open func attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey : Any] {
// statvfs(2) doesn't support 64bit inode on Darwin (apfs), fallback to statfs(2)
#if os(OSX) || os(iOS)
var s = statfs()
guard statfs(path, &s) == 0 else {
throw _NSErrorWithErrno(errno, reading: true, path: path)
}
#else
var s = statvfs()
guard statvfs(path, &s) == 0 else {
throw _NSErrorWithErrno(errno, reading: true, path: path)
}
#endif
var result = [FileAttributeKey : Any]()
#if os(OSX) || os(iOS)
let blockSize = UInt64(s.f_bsize)
result[.systemNumber] = NSNumber(value: UInt64(s.f_fsid.val.0))
#else
let blockSize = UInt64(s.f_frsize)
result[.systemNumber] = NSNumber(value: UInt64(s.f_fsid))
#endif
result[.systemSize] = NSNumber(value: blockSize * UInt64(s.f_blocks))
result[.systemFreeSize] = NSNumber(value: blockSize * UInt64(s.f_bavail))
result[.systemNodes] = NSNumber(value: UInt64(s.f_files))
result[.systemFreeNodes] = NSNumber(value: UInt64(s.f_ffree))
return result
}
#endif
/* createSymbolicLinkAtPath:withDestination:error: returns YES if the symbolic link that point at 'destPath' was able to be created at the location specified by 'path'. If this method returns NO, the link was unable to be created and an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink.
This method replaces createSymbolicLinkAtPath:pathContent:
*/
open func createSymbolicLink(atPath path: String, withDestinationPath destPath: String) throws {
if symlink(destPath, path) == -1 {
throw _NSErrorWithErrno(errno, reading: false, path: path)
}
}
/* destinationOfSymbolicLinkAtPath:error: returns an NSString containing the path of the item pointed at by the symlink specified by 'path'. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter.
This method replaces pathContentOfSymbolicLinkAtPath:
*/
open func destinationOfSymbolicLink(atPath path: String) throws -> String {
let bufSize = Int(PATH_MAX + 1)
var buf = [Int8](repeating: 0, count: bufSize)
let len = readlink(path, &buf, bufSize)
if len < 0 {
throw _NSErrorWithErrno(errno, reading: true, path: path)
}
return self.string(withFileSystemRepresentation: buf, length: Int(len))
}
open func copyItem(atPath srcPath: String, toPath dstPath: String) throws {
guard
let attrs = try? attributesOfItem(atPath: srcPath),
let fileType = attrs[.type] as? FileAttributeType
else {
return
}
if fileType == .typeDirectory {
try createDirectory(atPath: dstPath, withIntermediateDirectories: false, attributes: nil)
let subpaths = try subpathsOfDirectory(atPath: srcPath)
for subpath in subpaths {
try copyItem(atPath: srcPath + "/" + subpath, toPath: dstPath + "/" + subpath)
}
} else {
if createFile(atPath: dstPath, contents: contents(atPath: srcPath), attributes: nil) == false {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [NSFilePathErrorKey : NSString(string: dstPath)])
}
}
}
open func moveItem(atPath srcPath: String, toPath dstPath: String) throws {
guard !self.fileExists(atPath: dstPath) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteFileExists.rawValue, userInfo: [NSFilePathErrorKey : NSString(dstPath)])
}
if rename(srcPath, dstPath) != 0 {
if errno == EXDEV {
// TODO: Copy and delete.
NSUnimplemented("Cross-device moves not yet implemented")
} else {
throw _NSErrorWithErrno(errno, reading: false, path: srcPath)
}
}
}
open func linkItem(atPath srcPath: String, toPath dstPath: String) throws {
var isDir: ObjCBool = false
if self.fileExists(atPath: srcPath, isDirectory: &isDir) {
if !isDir.boolValue {
// TODO: Symlinks should be copied instead of hard-linked.
if link(srcPath, dstPath) == -1 {
throw _NSErrorWithErrno(errno, reading: false, path: srcPath)
}
} else {
// TODO: Recurse through directories, copying them.
NSUnimplemented("Recursive linking not yet implemented")
}
}
}
open func removeItem(atPath path: String) throws {
if rmdir(path) == 0 {
return
} else if errno == ENOTEMPTY {
let fsRep = FileManager.default.fileSystemRepresentation(withPath: path)
let ps = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 2)
ps.initialize(to: UnsafeMutablePointer(mutating: fsRep))
ps.advanced(by: 1).initialize(to: nil)
let stream = fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, nil)
ps.deinitialize(count: 2)
ps.deallocate(capacity: 2)
if stream != nil {
defer {
fts_close(stream)
}
var current = fts_read(stream)
while current != nil {
switch Int32(current!.pointee.fts_info) {
case FTS_DEFAULT, FTS_F, FTS_NSOK, FTS_SL, FTS_SLNONE:
if unlink(current!.pointee.fts_path) == -1 {
let str = NSString(bytes: current!.pointee.fts_path, length: Int(strlen(current!.pointee.fts_path)), encoding: String.Encoding.utf8.rawValue)!._swiftObject
throw _NSErrorWithErrno(errno, reading: false, path: str)
}
case FTS_DP:
if rmdir(current!.pointee.fts_path) == -1 {
let str = NSString(bytes: current!.pointee.fts_path, length: Int(strlen(current!.pointee.fts_path)), encoding: String.Encoding.utf8.rawValue)!._swiftObject
throw _NSErrorWithErrno(errno, reading: false, path: str)
}
default:
break
}
current = fts_read(stream)
}
} else {
let _ = _NSErrorWithErrno(ENOTEMPTY, reading: false, path: path)
}
// TODO: Error handling if fts_read fails.
} else if errno != ENOTDIR {
throw _NSErrorWithErrno(errno, reading: false, path: path)
} else if unlink(path) != 0 {
throw _NSErrorWithErrno(errno, reading: false, path: path)
}
}
open func copyItem(at srcURL: URL, to dstURL: URL) throws {
guard srcURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL])
}
guard dstURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL])
}
try copyItem(atPath: srcURL.path, toPath: dstURL.path)
}
open func moveItem(at srcURL: URL, to dstURL: URL) throws {
guard srcURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL])
}
guard dstURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL])
}
try moveItem(atPath: srcURL.path, toPath: dstURL.path)
}
open func linkItem(at srcURL: URL, to dstURL: URL) throws {
guard srcURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL])
}
guard dstURL.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL])
}
try linkItem(atPath: srcURL.path, toPath: dstURL.path)
}
open func removeItem(at url: URL) throws {
guard url.isFileURL else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url])
}
try self.removeItem(atPath: url.path)
}
/* Process working directory management. Despite the fact that these are instance methods on FileManager, these methods report and change (respectively) the working directory for the entire process. Developers are cautioned that doing so is fraught with peril.
*/
open var currentDirectoryPath: String {
let length = Int(PATH_MAX) + 1
var buf = [Int8](repeating: 0, count: length)
getcwd(&buf, length)
let result = self.string(withFileSystemRepresentation: buf, length: Int(strlen(buf)))
return result
}
@discardableResult
open func changeCurrentDirectoryPath(_ path: String) -> Bool {
return chdir(path) == 0
}
/* The following methods are of limited utility. Attempting to predicate behavior based on the current state of the filesystem or a particular file on the filesystem is encouraging odd behavior in the face of filesystem race conditions. It's far better to attempt an operation (like loading a file or creating a directory) and handle the error gracefully than it is to try to figure out ahead of time whether the operation will succeed.
*/
open func fileExists(atPath path: String) -> Bool {
return self.fileExists(atPath: path, isDirectory: nil)
}
open func fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool {
var s = stat()
if lstat(path, &s) >= 0 {
if let isDirectory = isDirectory {
if (s.st_mode & S_IFMT) == S_IFLNK {
if stat(path, &s) >= 0 {
isDirectory.pointee = ObjCBool((s.st_mode & S_IFMT) == S_IFDIR)
} else {
return false
}
} else {
let isDir = (s.st_mode & S_IFMT) == S_IFDIR
isDirectory.pointee = ObjCBool(isDir)
}
}
// don't chase the link for this magic case -- we might be /Net/foo
// which is a symlink to /private/Net/foo which is not yet mounted...
if (s.st_mode & S_IFMT) == S_IFLNK {
if (s.st_mode & S_ISVTX) == S_ISVTX {
return true
}
// chase the link; too bad if it is a slink to /Net/foo
stat(path, &s)
}
} else {
return false
}
return true
}
open func isReadableFile(atPath path: String) -> Bool {
return access(path, R_OK) == 0
}
open func isWritableFile(atPath path: String) -> Bool {
return access(path, W_OK) == 0
}
open func isExecutableFile(atPath path: String) -> Bool {
return access(path, X_OK) == 0
}
open func isDeletableFile(atPath path: String) -> Bool {
NSUnimplemented()
}
/* -contentsEqualAtPath:andPath: does not take into account data stored in the resource fork or filesystem extended attributes.
*/
open func contentsEqual(atPath path1: String, andPath path2: String) -> Bool {
NSUnimplemented()
}
/* displayNameAtPath: returns an NSString suitable for presentation to the user. For directories which have localization information, this will return the appropriate localized string. This string is not suitable for passing to anything that must interact with the filesystem.
*/
open func displayName(atPath path: String) -> String {
NSUnimplemented()
}
/* componentsToDisplayForPath: returns an NSArray of display names for the path provided. Localization will occur as in displayNameAtPath: above. This array cannot and should not be reassembled into an usable filesystem path for any kind of access.
*/
open func componentsToDisplay(forPath path: String) -> [String]? {
NSUnimplemented()
}
/* enumeratorAtPath: returns an NSDirectoryEnumerator rooted at the provided path. If the enumerator cannot be created, this returns NULL. Because NSDirectoryEnumerator is a subclass of NSEnumerator, the returned object can be used in the for...in construct.
*/
open func enumerator(atPath path: String) -> DirectoryEnumerator? {
return NSPathDirectoryEnumerator(path: path)
}
/* enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: returns an NSDirectoryEnumerator rooted at the provided directory URL. The NSDirectoryEnumerator returns NSURLs from the -nextObject method. The optional 'includingPropertiesForKeys' parameter indicates which resource properties should be pre-fetched and cached with each enumerated URL. The optional 'errorHandler' block argument is invoked when an error occurs. Parameters to the block are the URL on which an error occurred and the error. When the error handler returns YES, enumeration continues if possible. Enumeration stops immediately when the error handler returns NO.
If you wish to only receive the URLs and no other attributes, then pass '0' for 'options' and an empty NSArray ('[NSArray array]') for 'keys'. If you wish to have the property caches of the vended URLs pre-populated with a default set of attributes, then pass '0' for 'options' and 'nil' for 'keys'.
*/
// Note: Because the error handler is an optional block, the compiler treats it as @escaping by default. If that behavior changes, the @escaping will need to be added back.
open func enumerator(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: DirectoryEnumerationOptions = [], errorHandler handler: (/* @escaping */ (URL, Error) -> Bool)? = nil) -> DirectoryEnumerator? {
if mask.contains(.skipsPackageDescendants) || mask.contains(.skipsHiddenFiles) {
NSUnimplemented("Enumeration options not yet implemented")
}
return NSURLDirectoryEnumerator(url: url, options: mask, errorHandler: handler)
}
/* subpathsAtPath: returns an NSArray of all contents and subpaths recursively from the provided path. This may be very expensive to compute for deep filesystem hierarchies, and should probably be avoided.
*/
open func subpaths(atPath path: String) -> [String]? {
NSUnimplemented()
}
/* These methods are provided here for compatibility. The corresponding methods on NSData which return NSErrors should be regarded as the primary method of creating a file from an NSData or retrieving the contents of a file as an NSData.
*/
open func contents(atPath path: String) -> Data? {
do {
return try Data(contentsOf: URL(fileURLWithPath: path))
} catch {
return nil
}
}
open func createFile(atPath path: String, contents data: Data?, attributes attr: [FileAttributeKey : Any]? = nil) -> Bool {
do {
try (data ?? Data()).write(to: URL(fileURLWithPath: path), options: .atomic)
if let attr = attr {
try self.setAttributes(attr, ofItemAtPath: path)
}
return true
} catch _ {
return false
}
}
/* fileSystemRepresentationWithPath: returns an array of characters suitable for passing to lower-level POSIX style APIs. The string is provided in the representation most appropriate for the filesystem in question.
*/
open func fileSystemRepresentation(withPath path: String) -> UnsafePointer<Int8> {
precondition(path != "", "Empty path argument")
let len = CFStringGetMaximumSizeOfFileSystemRepresentation(path._cfObject)
if len == kCFNotFound {
fatalError("string could not be converted")
}
let buf = UnsafeMutablePointer<Int8>.allocate(capacity: len)
for i in 0..<len {
buf.advanced(by: i).initialize(to: 0)
}
if !path._nsObject.getFileSystemRepresentation(buf, maxLength: len) {
buf.deinitialize(count: len)
buf.deallocate(capacity: len)
fatalError("string could not be converted")
}
return UnsafePointer(buf)
}
/* stringWithFileSystemRepresentation:length: returns an NSString created from an array of bytes that are in the filesystem representation.
*/
open func string(withFileSystemRepresentation str: UnsafePointer<Int8>, length len: Int) -> String {
return NSString(bytes: str, length: len, encoding: String.Encoding.utf8.rawValue)!._swiftObject
}
/* -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: is for developers who wish to perform a safe-save without using the full NSDocument machinery that is available in the AppKit.
The `originalItemURL` is the item being replaced.
`newItemURL` is the item which will replace the original item. This item should be placed in a temporary directory as provided by the OS, or in a uniquely named directory placed in the same directory as the original item if the temporary directory is not available.
If `backupItemName` is provided, that name will be used to create a backup of the original item. The backup is placed in the same directory as the original item. If an error occurs during the creation of the backup item, the operation will fail. If there is already an item with the same name as the backup item, that item will be removed. The backup item will be removed in the event of success unless the `NSFileManagerItemReplacementWithoutDeletingBackupItem` option is provided in `options`.
For `options`, pass `0` to get the default behavior, which uses only the metadata from the new item while adjusting some properties using values from the original item. Pass `NSFileManagerItemReplacementUsingNewMetadataOnly` in order to use all possible metadata from the new item.
*/
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
open func replaceItem(at originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String?, options: ItemReplacementOptions = []) throws {
NSUnimplemented()
}
internal func _tryToResolveTrailingSymlinkInPath(_ path: String) -> String? {
guard _pathIsSymbolicLink(path) else {
return nil
}
guard let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: path) else {
return nil
}
return _appendSymlinkDestination(destination, toPath: path)
}
internal func _appendSymlinkDestination(_ dest: String, toPath: String) -> String {
if dest.hasPrefix("/") {
return dest
} else {
let temp = toPath._bridgeToObjectiveC().deletingLastPathComponent
return temp._bridgeToObjectiveC().appendingPathComponent(dest)
}
}
internal func _pathIsSymbolicLink(_ path: String) -> Bool {
guard
let attrs = try? attributesOfItem(atPath: path),
let fileType = attrs[.type] as? FileAttributeType
else {
return false
}
return fileType == .typeSymbolicLink
}
}
extension FileManager {
public func replaceItemAt(_ originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options: ItemReplacementOptions = []) throws -> NSURL? {
NSUnimplemented()
}
}
extension FileManager {
open var homeDirectoryForCurrentUser: URL {
return homeDirectory(forUser: CFCopyUserName().takeRetainedValue()._swiftObject)!
}
open var temporaryDirectory: URL {
return URL(fileURLWithPath: NSTemporaryDirectory())
}
open func homeDirectory(forUser userName: String) -> URL? {
guard !userName.isEmpty else { return nil }
guard let url = CFCopyHomeDirectoryURLForUser(userName._cfObject) else { return nil }
return url.takeRetainedValue()._swiftObject
}
}
extension FileManager {
public struct VolumeEnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
/* The mounted volume enumeration will skip hidden volumes.
*/
public static let skipHiddenVolumes = VolumeEnumerationOptions(rawValue: 1 << 1)
/* The mounted volume enumeration will produce file reference URLs rather than path-based URLs.
*/
public static let produceFileReferenceURLs = VolumeEnumerationOptions(rawValue: 1 << 2)
}
public struct DirectoryEnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
/* NSDirectoryEnumerationSkipsSubdirectoryDescendants causes the NSDirectoryEnumerator to perform a shallow enumeration and not descend into directories it encounters.
*/
public static let skipsSubdirectoryDescendants = DirectoryEnumerationOptions(rawValue: 1 << 0)
/* NSDirectoryEnumerationSkipsPackageDescendants will cause the NSDirectoryEnumerator to not descend into packages.
*/
public static let skipsPackageDescendants = DirectoryEnumerationOptions(rawValue: 1 << 1)
/* NSDirectoryEnumerationSkipsHiddenFiles causes the NSDirectoryEnumerator to not enumerate hidden files.
*/
public static let skipsHiddenFiles = DirectoryEnumerationOptions(rawValue: 1 << 2)
}
public struct ItemReplacementOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
/* Causes -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to use metadata from the new item only and not to attempt to preserve metadata from the original item.
*/
public static let usingNewMetadataOnly = ItemReplacementOptions(rawValue: 1 << 0)
/* Causes -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to leave the backup item in place after a successful replacement. The default behavior is to remove the item.
*/
public static let withoutDeletingBackupItem = ItemReplacementOptions(rawValue: 1 << 1)
}
public enum URLRelationship : Int {
case contains
case same
case other
}
}
public struct FileAttributeKey : RawRepresentable, Equatable, Hashable {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(_ lhs: FileAttributeKey, _ rhs: FileAttributeKey) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static let type = FileAttributeKey(rawValue: "NSFileType")
public static let size = FileAttributeKey(rawValue: "NSFileSize")
public static let modificationDate = FileAttributeKey(rawValue: "NSFileModificationDate")
public static let referenceCount = FileAttributeKey(rawValue: "NSFileReferenceCount")
public static let deviceIdentifier = FileAttributeKey(rawValue: "NSFileDeviceIdentifier")
public static let ownerAccountName = FileAttributeKey(rawValue: "NSFileOwnerAccountName")
public static let groupOwnerAccountName = FileAttributeKey(rawValue: "NSFileGroupOwnerAccountName")
public static let posixPermissions = FileAttributeKey(rawValue: "NSFilePosixPermissions")
public static let systemNumber = FileAttributeKey(rawValue: "NSFileSystemNumber")
public static let systemFileNumber = FileAttributeKey(rawValue: "NSFileSystemFileNumber")
public static let extensionHidden = FileAttributeKey(rawValue: "NSFileExtensionHidden")
public static let hfsCreatorCode = FileAttributeKey(rawValue: "NSFileHFSCreatorCode")
public static let hfsTypeCode = FileAttributeKey(rawValue: "NSFileHFSTypeCode")
public static let immutable = FileAttributeKey(rawValue: "NSFileImmutable")
public static let appendOnly = FileAttributeKey(rawValue: "NSFileAppendOnly")
public static let creationDate = FileAttributeKey(rawValue: "NSFileCreationDate")
public static let ownerAccountID = FileAttributeKey(rawValue: "NSFileOwnerAccountID")
public static let groupOwnerAccountID = FileAttributeKey(rawValue: "NSFileGroupOwnerAccountID")
public static let busy = FileAttributeKey(rawValue: "NSFileBusy")
public static let systemSize = FileAttributeKey(rawValue: "NSFileSystemSize")
public static let systemFreeSize = FileAttributeKey(rawValue: "NSFileSystemFreeSize")
public static let systemNodes = FileAttributeKey(rawValue: "NSFileSystemNodes")
public static let systemFreeNodes = FileAttributeKey(rawValue: "NSFileSystemFreeNodes")
}
public struct FileAttributeType : RawRepresentable, Equatable, Hashable {
public let rawValue: String
public init(_ rawValue: String) {
self.rawValue = rawValue
}
public init(rawValue: String) {
self.rawValue = rawValue
}
public var hashValue: Int {
return self.rawValue.hashValue
}
public static func ==(_ lhs: FileAttributeType, _ rhs: FileAttributeType) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static let typeDirectory = FileAttributeType(rawValue: "NSFileTypeDirectory")
public static let typeRegular = FileAttributeType(rawValue: "NSFileTypeRegular")
public static let typeSymbolicLink = FileAttributeType(rawValue: "NSFileTypeSymbolicLink")
public static let typeSocket = FileAttributeType(rawValue: "NSFileTypeSocket")
public static let typeCharacterSpecial = FileAttributeType(rawValue: "NSFileTypeCharacterSpecial")
public static let typeBlockSpecial = FileAttributeType(rawValue: "NSFileTypeBlockSpecial")
public static let typeUnknown = FileAttributeType(rawValue: "NSFileTypeUnknown")
}
public protocol FileManagerDelegate : NSObjectProtocol {
/* fileManager:shouldCopyItemAtPath:toPath: gives the delegate an opportunity to filter the resulting copy. Returning YES from this method will allow the copy to happen. Returning NO from this method causes the item in question to be skipped. If the item skipped was a directory, no children of that directory will be copied, nor will the delegate be notified of those children.
*/
func fileManager(_ fileManager: FileManager, shouldCopyItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldCopyItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: gives the delegate an opportunity to recover from or continue copying after an error. If an error occurs, the error object will contain an NSError indicating the problem. The source path and destination paths are also provided. If this method returns YES, the FileManager instance will continue as if the error had not occurred. If this method returns NO, the FileManager instance will stop copying, return NO from copyItemAtPath:toPath:error: and the error will be provied there.
*/
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldMoveItemAtPath:toPath: gives the delegate an opportunity to not move the item at the specified path. If the source path and the destination path are not on the same device, a copy is performed to the destination path and the original is removed. If the copy does not succeed, an error is returned and the incomplete copy is removed, leaving the original in place.
*/
func fileManager(_ fileManager: FileManager, shouldMoveItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldMoveItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldProceedAfterError:movingItemAtPath:toPath: functions much like fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: above. The delegate has the opportunity to remedy the error condition and allow the move to continue.
*/
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldLinkItemAtPath:toPath: acts as the other "should" methods, but this applies to the file manager creating hard links to the files in question.
*/
func fileManager(_ fileManager: FileManager, shouldLinkItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldLinkItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: allows the delegate an opportunity to remedy the error which occurred in linking srcPath to dstPath. If the delegate returns YES from this method, the linking will continue. If the delegate returns NO from this method, the linking operation will stop and the error will be returned via linkItemAtPath:toPath:error:.
*/
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAtPath srcPath: String, toPath dstPath: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAt srcURL: URL, to dstURL: URL) -> Bool
/* fileManager:shouldRemoveItemAtPath: allows the delegate the opportunity to not remove the item at path. If the delegate returns YES from this method, the FileManager instance will attempt to remove the item. If the delegate returns NO from this method, the remove skips the item. If the item is a directory, no children of that item will be visited.
*/
func fileManager(_ fileManager: FileManager, shouldRemoveItemAtPath path: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldRemoveItemAt URL: URL) -> Bool
/* fileManager:shouldProceedAfterError:removingItemAtPath: allows the delegate an opportunity to remedy the error which occurred in removing the item at the path provided. If the delegate returns YES from this method, the removal operation will continue. If the delegate returns NO from this method, the removal operation will stop and the error will be returned via linkItemAtPath:toPath:error:.
*/
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAtPath path: String) -> Bool
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAt URL: URL) -> Bool
}
extension FileManagerDelegate {
func fileManager(_ fileManager: FileManager, shouldCopyItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldCopyItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldMoveItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldMoveItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldLinkItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldLinkItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldRemoveItemAtPath path: String) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldRemoveItemAtURL url: URL) -> Bool { return true }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAtPath path: String) -> Bool { return false }
func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAtURL url: URL) -> Bool { return false }
}
extension FileManager {
open class DirectoryEnumerator : NSEnumerator {
/* For NSDirectoryEnumerators created with -enumeratorAtPath:, the -fileAttributes and -directoryAttributes methods return an NSDictionary containing the keys listed below. For NSDirectoryEnumerators created with -enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:, these two methods return nil.
*/
open var fileAttributes: [FileAttributeKey : Any]? {
NSRequiresConcreteImplementation()
}
open var directoryAttributes: [FileAttributeKey : Any]? {
NSRequiresConcreteImplementation()
}
/* This method returns the number of levels deep the current object is in the directory hierarchy being enumerated. The directory passed to -enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: is considered to be level 0.
*/
open var level: Int {
NSRequiresConcreteImplementation()
}
open func skipDescendants() {
NSRequiresConcreteImplementation()
}
}
internal class NSPathDirectoryEnumerator: DirectoryEnumerator {
let baseURL: URL
let innerEnumerator : DirectoryEnumerator
override var fileAttributes: [FileAttributeKey : Any]? {
NSUnimplemented()
}
override var directoryAttributes: [FileAttributeKey : Any]? {
NSUnimplemented()
}
override var level: Int {
NSUnimplemented()
}
override func skipDescendants() {
NSUnimplemented()
}
init?(path: String) {
let url = URL(fileURLWithPath: path)
self.baseURL = url
guard let ie = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil, options: [], errorHandler: nil) else {
return nil
}
self.innerEnumerator = ie
}
override func nextObject() -> Any? {
let o = innerEnumerator.nextObject()
guard let url = o as? URL else {
return nil
}
let path = url.path.replacingOccurrences(of: baseURL.path+"/", with: "")
return path
}
}
internal class NSURLDirectoryEnumerator : DirectoryEnumerator {
var _url : URL
var _options : FileManager.DirectoryEnumerationOptions
var _errorHandler : ((URL, Error) -> Bool)?
var _stream : UnsafeMutablePointer<FTS>? = nil
var _current : UnsafeMutablePointer<FTSENT>? = nil
var _rootError : Error? = nil
var _gotRoot : Bool = false
// See @escaping comments above.
init(url: URL, options: FileManager.DirectoryEnumerationOptions, errorHandler: (/* @escaping */ (URL, Error) -> Bool)?) {
_url = url
_options = options
_errorHandler = errorHandler
if FileManager.default.fileExists(atPath: _url.path) {
let fsRep = FileManager.default.fileSystemRepresentation(withPath: _url.path)
let ps = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 2)
ps.initialize(to: UnsafeMutablePointer(mutating: fsRep))
ps.advanced(by: 1).initialize(to: nil)
_stream = fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, nil)
ps.deinitialize(count: 2)
ps.deallocate(capacity: 2)
} else {
_rootError = _NSErrorWithErrno(ENOENT, reading: true, url: url)
}
}
deinit {
if let stream = _stream {
fts_close(stream)
}
}
override func nextObject() -> Any? {
if let stream = _stream {
if !_gotRoot {
_gotRoot = true
// Skip the root.
_current = fts_read(stream)
}
_current = fts_read(stream)
while let current = _current {
switch Int32(current.pointee.fts_info) {
case FTS_D:
if _options.contains(.skipsSubdirectoryDescendants) {
fts_set(_stream, _current, FTS_SKIP)
}
fallthrough
case FTS_DEFAULT, FTS_F, FTS_NSOK, FTS_SL, FTS_SLNONE:
let str = NSString(bytes: current.pointee.fts_path, length: Int(strlen(current.pointee.fts_path)), encoding: String.Encoding.utf8.rawValue)!._swiftObject
return URL(fileURLWithPath: str)
case FTS_DNR, FTS_ERR, FTS_NS:
let keepGoing : Bool
if let handler = _errorHandler {
let str = NSString(bytes: current.pointee.fts_path, length: Int(strlen(current.pointee.fts_path)), encoding: String.Encoding.utf8.rawValue)!._swiftObject
keepGoing = handler(URL(fileURLWithPath: str), _NSErrorWithErrno(current.pointee.fts_errno, reading: true))
} else {
keepGoing = true
}
if !keepGoing {
fts_close(stream)
_stream = nil
return nil
}
default:
break
}
_current = fts_read(stream)
}
// TODO: Error handling if fts_read fails.
} else if let error = _rootError {
// Was there an error opening the stream?
if let handler = _errorHandler {
let _ = handler(_url, error)
}
}
return nil
}
override var directoryAttributes : [FileAttributeKey : Any]? {
return nil
}
override var fileAttributes: [FileAttributeKey : Any]? {
return nil
}
override var level: Int {
return Int(_current?.pointee.fts_level ?? 0)
}
override func skipDescendants() {
if let stream = _stream, let current = _current {
fts_set(stream, current, FTS_SKIP)
}
}
}
}
|
apache-2.0
|
a119a3317731abce36e43cefa537cf17
| 53.516071 | 771 | 0.660356 | 5.121456 | false | false | false | false |
kevintavog/PeachMetadata
|
source/PeachMetadata/ImportMediaWindowsController.swift
|
1
|
11725
|
//
// ImportMediaWindowsController.swift
//
import AppKit
import Async
import RangicCore
class ImportMediaWindowsController : NSWindowController, NSTableViewDataSource
{
static fileprivate let missingAttrs = [
NSAttributedStringKey.foregroundColor : NSColor(deviceRed: 0.0, green: 0.7, blue: 0.7, alpha: 1.0),
NSAttributedStringKey.font : NSFont.labelFont(ofSize: 14)
]
static fileprivate let badDataAttrs = [
NSAttributedStringKey.foregroundColor : NSColor.orange,
NSAttributedStringKey.font : NSFont.labelFont(ofSize: 14)
]
static fileprivate func applyAttributes(_ text: String, attributes: [NSAttributedStringKey:AnyObject]) -> NSAttributedString
{
let fullRange = NSRange(location: 0, length: text.count)
let attributeString = NSMutableAttributedString(string: text)
for attr in attributes {
attributeString.addAttribute(attr.0, value: attr.1, range: fullRange)
}
return attributeString
}
@IBOutlet var progressController: ImportProgressWindowsController!
fileprivate let OriginalTableTag = 1
fileprivate let ExportedTableTag = 2
fileprivate let WarningsTableTag = 3
fileprivate let FilenameColumnIdentifier = "Filename"
fileprivate let TimestampColumnIdentifier = "Timestamp"
fileprivate let TimestampStatusColumnIdentifier = "TimestampStatus"
fileprivate let LocationColumnIdentifier = "Location"
fileprivate let LocationStatusColumnIdentifier = "LocationStatus"
@IBOutlet weak var importFolderLabel: NSTextField!
@IBOutlet weak var exportFolderLabel: NSTextField!
@IBOutlet weak var importTable: NSTableView!
@IBOutlet weak var exportTable: NSTableView!
fileprivate var firstDidBecomeKey = true
fileprivate var importFolderName: String?
var exportFolderName: String?
var yearForMaster: String?
var originalMediaData = [MediaData]()
var exportedMediaData = [MediaData]()
var warnings = [String]()
// Must be called to setup data - returns false if the import is not supported
func setImportFolder(_ path: String) -> Bool
{
Logger.info("importMedia from \(path)")
if loadFileData(path) {
importFolderName = path
return true
}
return false
}
override func awakeFromNib()
{
importFolderLabel.stringValue = importFolderName!
exportFolderLabel.stringValue = exportFolderName!
}
func windowDidBecomeKey(_ notification: Notification)
{
if firstDidBecomeKey {
exportFolderLabel.currentEditor()?.moveToEndOfLine(self)
firstDidBecomeKey = false
}
}
@IBAction func importMedia(_ sender: AnyObject)
{
if exportFolderName == exportFolderLabel.stringValue {
PeachWindowController.showWarning("The destination folder name must be different from the date.\r\r Currently: '\(exportFolderLabel.stringValue)'")
return
}
// Confirm the folder name has been changed (isn't date only); allow to pass if OK
// How to handle if destination folder already exists? Perhaps confirm that a merge is what's desired
let picturesFolder = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask).first!.path
let folder = NSString.path(withComponents: [picturesFolder, "Master", yearForMaster!, exportFolderLabel.stringValue])
if !warnings.isEmpty {
if !PeachWindowController.askQuestion("Do you want to import with \(warnings.count) warning(s)?") {
return
}
}
close()
progressController.start(importFolderName!, destinationFolder: folder, originalMediaData: originalMediaData, exportedMediaData: exportedMediaData)
NSApplication.shared.stopModal(withCode: NSApplication.ModalResponse(rawValue: 1))
}
@IBAction func cancel(_ sender: AnyObject)
{
close()
NSApplication.shared.stopModal(withCode: NSApplication.ModalResponse(rawValue: 0))
}
func numberOfRows(in tableView: NSTableView) -> Int
{
switch tableView.tag {
case OriginalTableTag:
return originalMediaData.count
case ExportedTableTag:
return exportedMediaData.count
case WarningsTableTag:
return warnings.count
default:
Logger.error("Unsupported tableView: \(tableView.tag)")
return 0
}
}
// If @nonobjc is added here, per the warning, then nothing shows up in the tables...
public func tableView(_ tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView?
{
let cell = tableView.makeView(withIdentifier: tableColumn!.identifier, owner: self) as! NSTableCellView
var media: MediaData!
switch tableView.tag {
case OriginalTableTag:
media = originalMediaData[row]
case ExportedTableTag:
media = exportedMediaData[row]
case WarningsTableTag:
cell.textField?.stringValue = warnings[row]
return cell
default:
Logger.error("Unsupported tableView: \(tableView.tag)")
}
if let data = media {
let missingLocation = data.location == nil
let sensitiveLocation = !missingLocation && SensitiveLocations.sharedInstance.isSensitive(data.location!)
switch tableColumn!.identifier.rawValue {
case FilenameColumnIdentifier:
cell.textField?.stringValue = data.name
case TimestampColumnIdentifier:
if data.doFileAndExifTimestampsMatch() {
cell.textField?.stringValue = data.formattedTime()
} else {
cell.textField?.attributedStringValue = ImportMediaWindowsController.applyAttributes(data.formattedTime(), attributes: ImportMediaWindowsController.badDataAttrs)
}
case TimestampStatusColumnIdentifier:
if data.doFileAndExifTimestampsMatch() {
cell.imageView?.image = nil
} else {
cell.imageView?.image = NSImage(imageLiteralResourceName: "timestampBad")
}
case LocationColumnIdentifier:
if missingLocation {
cell.textField?.attributedStringValue = ImportMediaWindowsController.applyAttributes("< missing >", attributes: ImportMediaWindowsController.missingAttrs)
} else if sensitiveLocation {
cell.textField?.attributedStringValue = ImportMediaWindowsController.applyAttributes(data.locationString(), attributes: ImportMediaWindowsController.badDataAttrs)
} else {
cell.textField?.stringValue = data.locationString()
}
case LocationStatusColumnIdentifier:
if missingLocation {
cell.imageView?.image = NSImage(imageLiteralResourceName: "locationMissing")
} else if sensitiveLocation {
cell.imageView?.image = NSImage(imageLiteralResourceName: "locationBad")
} else {
cell.imageView?.image = nil
}
default:
Logger.error("Unsupported column \(tableColumn!.identifier)")
}
}
return cell;
}
func loadFileData(_ path: String) -> Bool
{
// Get subfolders - must have ONLY 'Exported'
let (folders, originalFiles) = getFoldersAndFiles(path)
if folders.count != 1 {
PeachWindowController.showWarning("Import supports only a single folder, found \(folders.count)")
return false
}
if folders.first!.lastPathComponent != "Exported" {
PeachWindowController.showWarning("Import requires a folder named 'Exported'; found '\(String(describing: folders.first))'")
return false
}
let (exportedFolders, exportedFiles) = getFoldersAndFiles(folders.first!.path)
if exportedFolders.count != 0 {
PeachWindowController.showWarning("The 'Exported' has at least one subfolder - but shouldn't have any")
return false
}
var hasVideos = false
var unsupportedFiles = [String]()
for original in originalFiles {
let mediaType = SupportedMediaTypes.getType(original)
if mediaType != .unknown {
if mediaType == .video {
hasVideos = true
}
originalMediaData.append(FileMediaData.create(original, mediaType: mediaType))
} else {
unsupportedFiles.append(original.lastPathComponent)
}
}
for exported in exportedFiles {
let mediaType = SupportedMediaTypes.getType(exported)
if mediaType != .unknown {
let mediaData = FileMediaData.create(exported, mediaType: mediaType)
exportedMediaData.append(mediaData)
if !mediaData.doFileAndExifTimestampsMatch() {
let _ = mediaData.setFileDateToExifDate()
}
} else {
unsupportedFiles.append(exported.lastPathComponent)
}
}
if unsupportedFiles.count != 0 {
PeachWindowController.showWarning("Found unsupported files: \(unsupportedFiles.joined(separator: ", "))")
return false
}
if exportedMediaData.count == 0 && !hasVideos {
PeachWindowController.showWarning("No exported files were found")
return false
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let yearDateFormatter = DateFormatter()
yearDateFormatter.dateFormat = "yyyy"
if exportedMediaData.count > 0 {
exportFolderName = dateFormatter.string(from: exportedMediaData.first!.timestamp!) + " "
yearForMaster = yearDateFormatter.string(from: exportedMediaData.first!.timestamp!)
} else {
exportFolderName = dateFormatter.string(from: originalMediaData.first!.timestamp!) + " "
yearForMaster = yearDateFormatter.string(from: originalMediaData.first!.timestamp!)
}
let importer = ImportLightroomExport(originalMediaData: originalMediaData, exportedMediaData: exportedMediaData)
warnings = importer.findWarnings();
return true
}
// Return the folders and files from a given path
func getFoldersAndFiles(_ path: String) -> (folders: [URL], files: [URL])
{
var folders = [URL]()
var files = [URL]()
if let allChildren = getFiles(path) {
for child in allChildren {
var isFolder: ObjCBool = false
if FileManager.default.fileExists(atPath: child.path, isDirectory:&isFolder) && isFolder.boolValue {
folders.append(child)
} else {
files.append(child)
}
}
}
return (folders, files)
}
fileprivate func getFiles(_ folderName: String) -> [URL]?
{
do {
return try FileManager.default.contentsOfDirectory(
at: URL(fileURLWithPath: folderName),
includingPropertiesForKeys: nil,
options:FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
}
catch let error {
Logger.error("Failed getting files in \(folderName): \(error)")
return nil
}
}
}
|
mit
|
6f63e63046c8742e5a2cf912ec0fbc37
| 37.316993 | 182 | 0.634115 | 5.40821 | false | false | false | false |
manderson-productions/Spreken
|
Spreken/SpeechRecognition/SpeechInput.swift
|
1
|
3096
|
//
// SpeechInput.swift
// Spreken
//
// Created by Mark Anderson on 9/10/16.
// Copyright © 2016 manderson-productions. All rights reserved.
//
import Foundation
import Speech
typealias AuthorizationStatus = SFSpeechRecognizerAuthorizationStatus
final class SpeechInput: NSObject, SFSpeechRecognizerDelegate {
fileprivate let recognizer: SFSpeechRecognizer
fileprivate var recognitionRequest: SFSpeechAudioBufferRecognitionRequest?
fileprivate var recognitionTask: SFSpeechRecognitionTask?
public var recognitionHandler: ((_ bestGuess: String) -> Void)?
init?(locale: Locale) {
guard let recognizer = SFSpeechRecognizer(locale: locale) else {
print("Init failed for speech recognition")
return nil
}
self.recognizer = recognizer
self.recognitionHandler = nil
super.init()
self.recognizer.delegate = self
}
public func authorize(handler: @escaping (AuthorizationStatus) -> Void) {
SFSpeechRecognizer.requestAuthorization(handler)
}
public func beginRecognition() -> Bool {
guard SFSpeechRecognizer.authorizationStatus() == .authorized else { return false }
// Cancel the previous task if it's running.
if let recognitionTask = self.recognitionTask {
recognitionTask.cancel()
self.recognitionTask = nil
}
self.recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
guard let recognitionRequest = self.recognitionRequest else { fatalError("Unable to created a SFSpeechAudioBufferRecognitionRequest object") }
recognitionRequest.shouldReportPartialResults = false
self.recognitionTask = self.recognizer.recognitionTask(with: recognitionRequest) { [weak self] (result, error) in
var isFinal = false
if let result = result {
isFinal = result.isFinal
if isFinal {
self?.recognitionHandler?(result.bestTranscription.formattedString)
}
}
if error != nil || isFinal {
AudioEngine.sharedInstance.removeTap()
self?.recognitionRequest = nil
self?.recognitionTask = nil
print("Done recording")
}
}
AudioEngine.sharedInstance.setup(category: .record)
AudioEngine.sharedInstance.installTap({ [weak self] (buffer: AVAudioPCMBuffer, when: AVAudioTime) in
self?.recognitionRequest?.append(buffer)
})
do {
try AudioEngine.sharedInstance.start()
} catch {
print("Error: Could not start the AudioEngine: \(error)")
return false
}
return true
}
public func endRecognition() {
self.recognitionRequest?.endAudio()
}
// MARK: SFSpeechRecognizer Delegate
func speechRecognizer(_ speechRecognizer: SFSpeechRecognizer, availabilityDidChange available: Bool) {
print("Speech recognizer is now \(available ? "available" : "unavailable")")
}
}
|
apache-2.0
|
ea9fa8c456720fa0f0903b913e010dfa
| 30.907216 | 150 | 0.65105 | 5.806754 | false | false | false | false |
andersio/MantleData
|
MantleData/ObjectCollectionPrefetcher.swift
|
1
|
9319
|
//
// ObjectCollectionPrefetcher.swift
// MantleData
//
// Created by Anders on 7/5/2016.
// Copyright © 2016 Anders. All rights reserved.
//
import CoreData
/// ObjectCollection Prefetcher
public enum ObjectCollectionPrefetchingPolicy {
case none
case all
case adjacent(batchSize: Int)
}
internal class ObjectCollectionPrefetcher<E: NSManagedObject> {
func reset() {
_abstractMethod_subclassMustImplement()
}
func acknowledgeNextAccess(at row: Int, in section: Int) {
_abstractMethod_subclassMustImplement()
}
func acknowledgeFetchCompletion(_ objectCount: Int) {
_abstractMethod_subclassMustImplement()
}
func acknowledgeChanges(inserted insertedIds: [SectionKey: Box<Set<ObjectReference<E>>>], deleted deletedIds: [Box<Set<ObjectReference<E>>>]) {
_abstractMethod_subclassMustImplement()
}
}
/// LinearBatchingPrefetcher
private enum LastUsedPool {
case first
case second
}
internal final class LinearBatchingPrefetcher<E: NSManagedObject>: ObjectCollectionPrefetcher<E> {
weak var objectSet: ObjectCollection<E>!
private var firstPool: [E]?
private var secondPool: [E]?
private var nextPool: LastUsedPool
private let batchSize: Int
private let halfOfBatch: Int
var lastAccessedIndex: Int
var prefetchedRange: CountableRange<Int>
init(for objectSet: ObjectCollection<E>, batchSize: Int) {
assert(batchSize % 2 == 0)
self.objectSet = objectSet
self.batchSize = batchSize
self.halfOfBatch = batchSize / 2
self.lastAccessedIndex = -batchSize
self.prefetchedRange = 0 ..< 0
self.nextPool = .first
}
override func reset() {
firstPool = nil
secondPool = nil
nextPool = .first
prefetchedRange = 0 ..< 0
}
func flattenedIndex(for row: Int, in section: Int) -> Int? {
guard section < objectSet.count else {
return nil
}
var flattenedIndex = 0
for index in 0 ..< section {
flattenedIndex += objectSet.sections[index].count
}
return flattenedIndex + row
}
func expandedIndices(at flattenedPosition: Int) -> (section: Int, row: Int)? {
if flattenedPosition < 0 {
return nil
}
var remaining = flattenedPosition
for index in objectSet.sections.indices {
let count = objectSet.sections[index].count
if count > 0 {
if remaining >= count {
remaining -= count
} else {
return (section: index, row: remaining)
}
}
}
return nil
}
func expandedIndicesWithCapping(at flattenedPosition: Int, forForwardPrefetching: Bool) -> (section: Int, row: Int) {
if let indices = expandedIndices(at: flattenedPosition) {
return indices
}
if forForwardPrefetching {
return (section: objectSet.sections.endIndex - 1,
row: objectSet.sections[objectSet.sections.endIndex - 1].endIndex - 1)
} else {
return (section: 0, row: 0)
}
}
func obtainIDsForBatch(at flattenedPosition: Int, forward isForwardPrefetching: Bool) -> [NSManagedObject] {
var prefetchingIds = [ArraySlice<ObjectReference<E>>]()
var (iteratingSectionIndex, iteratingPosition) = expandedIndicesWithCapping(at: flattenedPosition,
forForwardPrefetching: isForwardPrefetching)
var delta = halfOfBatch
let sectionIndices = objectSet.sections.indices
while delta != 0 &&
sectionIndices.contains(iteratingSectionIndex) &&
iteratingPosition >= objectSet.sections[iteratingSectionIndex].startIndex {
if isForwardPrefetching {
let sectionEndIndex = objectSet.sections[iteratingSectionIndex].storage.endIndex
let endIndex = objectSet.sections[iteratingSectionIndex].index(iteratingPosition,
offsetBy: delta,
limitedBy: sectionEndIndex) ?? sectionEndIndex
delta = delta - (endIndex - iteratingPosition)
let range = iteratingPosition ..< endIndex
let slice = objectSet.sections[iteratingSectionIndex].storage[range]
prefetchingIds.append(slice)
} else {
let sectionStartIndex = objectSet.sections[iteratingSectionIndex].storage.startIndex
let startIndex = objectSet.sections[iteratingSectionIndex].index(iteratingPosition,
offsetBy: -delta,
limitedBy: sectionStartIndex) ?? sectionStartIndex
delta = delta - (iteratingPosition - startIndex)
let range = startIndex ..< iteratingPosition
let slice = objectSet.sections[iteratingSectionIndex].storage[range]
prefetchingIds.append(slice)
}
iteratingSectionIndex += isForwardPrefetching ? 1 : -1
if iteratingSectionIndex >= objectSet.sections.startIndex {
iteratingPosition = isForwardPrefetching ? 0 : objectSet.sections[iteratingSectionIndex].endIndex
}
}
return prefetchingIds
.flatMap { $0 }
.flatMap { $0.wrapped.objectID.isTemporaryID ? nil : $0.wrapped }
}
func prefetch(at flattenedPosition: Int, forward isForwardPrefetching: Bool) throws {
let prefetchingIds = obtainIDsForBatch(at: flattenedPosition,
forward: isForwardPrefetching)
let prefetchRequest = NSFetchRequest<E>()
prefetchRequest.entity = E.entity(in: objectSet.context)
prefetchRequest.predicate = NSPredicate(format: "self IN %@",
argumentArray: [prefetchingIds as NSArray])
prefetchRequest.resultType = []
prefetchRequest.relationshipKeyPathsForPrefetching = objectSet.prefetchingRelationships
prefetchRequest.returnsObjectsAsFaults = false
let prefetchedObjects = try objectSet.context.fetch(prefetchRequest)
retain(prefetchedObjects)
}
func retain(_ objects: [E]) {
switch nextPool {
case .first:
firstPool = objects
nextPool = .second
case .second:
secondPool = objects
nextPool = .first
}
}
override func acknowledgeNextAccess(at row: Int, in section: Int) {
guard let currentPosition = flattenedIndex(for: row, in: section) else {
return
}
defer {
lastAccessedIndex = currentPosition
}
do {
let isMovingForward = currentPosition - lastAccessedIndex >= 0
if currentPosition % halfOfBatch == 0 && (currentPosition != 0 || isMovingForward) {
try prefetch(at: currentPosition, forward: isMovingForward)
prefetchedRange = currentPosition - halfOfBatch + 1 ..< currentPosition + halfOfBatch
}
} catch let error {
print("LinearBatchingPrefetcher<\(String(describing: E.self))>: cannot execute batch of prefetch at row \(row) in section \(section). Error: \(error)")
}
}
override func acknowledgeFetchCompletion(_ objectCount: Int) {}
override func acknowledgeChanges(inserted insertedIds: [SectionKey: Box<Set<ObjectReference<E>>>], deleted deletedIds: [Box<Set<ObjectReference<E>>>]) {}
}
/// GreedyPrefetcher
internal final class GreedyPrefetcher<E: NSManagedObject>: ObjectCollectionPrefetcher<E> {
var retainingPool = Set<NSManagedObject>()
unowned var objectSet: ObjectCollection<E>
init(for objectSet: ObjectCollection<E>) {
self.objectSet = objectSet
}
override func reset() {}
override func acknowledgeNextAccess(at row: Int, in section: Int) {}
override func acknowledgeFetchCompletion(_ objectCount: Int) {
var allObjects = [E]()
allObjects.reserveCapacity(objectCount)
for index in objectSet.sections.indices {
let objects = objectSet.sections[index].storage
.flatMap { $0.wrapped.objectID.isTemporaryID ? nil : $0.wrapped }
allObjects.append(contentsOf: objects)
}
let prefetchRequest = NSFetchRequest<NSManagedObject>()
prefetchRequest.entity = E.entity(in: objectSet.context)
prefetchRequest.predicate = NSPredicate(format: "self IN %@",
argumentArray: [allObjects as NSArray])
prefetchRequest.resultType = []
prefetchRequest.relationshipKeyPathsForPrefetching = objectSet.prefetchingRelationships
prefetchRequest.returnsObjectsAsFaults = false
do {
let prefetchedObjects = try objectSet.context.fetch(prefetchRequest)
retainingPool.formUnion(prefetchedObjects)
} catch let error {
print("GreedyPrefetcher<\(String(describing: E.self))>: cannot execute a prefetch. Error: \(error)")
}
}
override func acknowledgeChanges(inserted insertedIds: [SectionKey: Box<Set<ObjectReference<E>>>], deleted deletedIds: [Box<Set<ObjectReference<E>>>]) {
for ids in deletedIds {
for id in ids.value {
retainingPool.remove(id.wrapped)
}
}
let inserted = insertedIds
.flatMap { $0.1.value }
.flatMap { $0.wrapped.objectID.isTemporaryID ? nil : $0.wrapped }
if !insertedIds.isEmpty {
let prefetchRequest = NSFetchRequest<NSManagedObject>()
prefetchRequest.entity = E.entity(in: objectSet.context)
prefetchRequest.predicate = NSPredicate(format: "self IN %@", inserted as NSArray)
prefetchRequest.resultType = []
prefetchRequest.relationshipKeyPathsForPrefetching = objectSet.prefetchingRelationships
prefetchRequest.returnsObjectsAsFaults = false
do {
let prefetchedObjects = try objectSet.context.fetch(prefetchRequest)
retainingPool.formUnion(prefetchedObjects)
} catch let error {
print("GreedyPrefetcher<\(String(describing: E.self))>: cannot execute a prefetch. Error: \(error)")
}
}
}
}
|
mit
|
75b97ae88c48902f744579e25b2b064b
| 31.694737 | 154 | 0.705838 | 4.044271 | false | false | false | false |
kyleduo/TinyPNG4Mac
|
source/tinypng4mac/views/InputKeyAlert.swift
|
1
|
2581
|
//
// InputKeyAlert.swift
// tinypng4mac
//
// Created by kyle on 16/7/7.
// Copyright © 2016年 kyleduo. All rights reserved.
//
import Cocoa
class InputKeyAlert: NSAlert, NSTextFieldDelegate {
var input: NSTextField?
var submitButton: NSButton?
var cancelButton: NSButton?
var isShowing = false
override init() {
super.init()
self.messageText = NSLocalizedString("Input developer API Key. If you do not have, click register button.", comment: "Input developer API Key. If you do not have, click register button.")
let view = NSView.init(frame: CGRect(x: 0, y: 0, width: 300, height: 54))
self.input = NSTextField.init(frame: CGRect(x: 0, y: 30, width: 300, height: 24))
self.input?.delegate = self
self.input?.usesSingleLineMode = true
view.addSubview(self.input!)
let button = self.createRegisterButton()
view.addSubview(button)
self.accessoryView = view
submitButton = self.addButton(withTitle: NSLocalizedString("Save", comment: "Save"))
submitButton?.isEnabled = false
cancelButton = self.addButton(withTitle: NSLocalizedString("Later", comment: "Later"))
}
func createRegisterButton() -> NSButton {
let button = NSButton.init(frame: CGRect(x: 0, y: 0, width: 56, height: 24))
button.setButtonType(NSButton.ButtonType.momentaryLight)
button.isBordered = false
let paragraphStyle = NSMutableParagraphStyle.init()
paragraphStyle.alignment = NSTextAlignment.center
let title = NSMutableAttributedString.init(string: NSLocalizedString("Register", comment: "Register"))
title.addAttributes([NSAttributedString.Key.foregroundColor: NSColor.linkColor,
NSAttributedString.Key.paragraphStyle:paragraphStyle,
NSAttributedString.Key.underlineStyle:NSUnderlineStyle.single.rawValue], range: NSMakeRange(0, title.length))
button.attributedTitle = title
button.target = self
button.action = #selector(InputKeyAlert.gotoRegister)
return button
}
@objc func gotoRegister() {
NSWorkspace.shared.open(URL.init(string: "https://tinypng.com/developers")!)
}
func show(_ window: NSWindow!, saveAction: ((String?) -> Void)?) {
isShowing = true
self.beginSheetModal(for: window, completionHandler: { (response) in
self.isShowing = false
if response == NSApplication.ModalResponse.alertFirstButtonReturn {
saveAction?(self.input?.stringValue)
}
})
}
func controlTextDidChange(_ obj: Notification) {
if let text = input?.stringValue {
self.submitButton?.isEnabled = text.count > 0
}
}
}
|
mit
|
b4cc75c6a8a807e8b9c9068e7cfcf964
| 35.828571 | 189 | 0.711016 | 4.009331 | false | false | false | false |
EmberTown/ember-hearth
|
Ember Hearth/PaddedTextFieldCell.swift
|
1
|
780
|
//
// PaddedTextFieldCell.swift
// Ember Hearth
//
// Created by Thomas Sunde Nielsen on 07.04.15.
// Copyright (c) 2015 Thomas Sunde Nielsen. All rights reserved.
//
import Cocoa
// Couldn't figure out what redraw function to call in didSet on each var to make this an IBDesignable.
class PaddedTextFieldCell: NSTextFieldCell {
var paddingLeft: CGFloat = 10.0
var paddingRight: CGFloat = 10.0
var paddingTop: CGFloat = 15.0
var paddingBottom: CGFloat = 5.0
override func drawingRectForBounds(theRect: NSRect) -> NSRect {
let inset = NSMakeRect(theRect.origin.x + paddingLeft, theRect.origin.y + paddingTop, theRect.size.width - paddingLeft - paddingRight, theRect.size.height - paddingTop - paddingBottom)
return inset
}
}
|
mit
|
ff0c09b9eca0e52509001da86fdfa06e
| 32.913043 | 192 | 0.711538 | 4.08377 | false | false | false | false |
material-motion/material-motion-swift
|
src/transitions/ViewControllerDismisser.swift
|
2
|
4287
|
/*
Copyright 2016-present The Material Motion 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.
*/
import Foundation
import UIKit
/**
A view controller dismisser is responsible for initiating a view controller dismiss transition in
reaction to a gesture recognizer entering its began or recognized state.
Gesture recognizers provided to a dismisser will be made available to the transition instance via
the TransitionContext's `gestureRecognizers` property.
*/
public final class ViewControllerDismisser {
/**
Start a dismiss transition when the given gesture recognizer enters its began or recognized
state.
The provided gesture recognizer will be made available to the transition instance via the
TransitionContext's `gestureRecognizers` property.
*/
public func dismissWhenGestureRecognizerBegins(_ gestureRecognizer: UIGestureRecognizer) {
gestureRecognizer.addTarget(self, action: #selector(gestureRecognizerDidChange))
if gestureRecognizer.delegate == nil {
gestureRecognizer.delegate = gestureDelegate
}
gestureDelegate.gestureRecognizers.insert(gestureRecognizer)
}
public func disableSimultaneousRecognition(of gestureRecognizer: UIGestureRecognizer) {
gestureDelegate.soloGestureRecognizers.insert(gestureRecognizer)
}
/**
Returns a gesture recognizer delegate that will allow the gesture recognizer to begin only if the
provided scroll view is scrolled to the top of its content.
The returned delegate implements gestureRecognizerShouldBegin.
*/
public func topEdgeDismisserDelegate(for scrollView: UIScrollView) -> UIGestureRecognizerDelegate {
for delegate in scrollViewTopEdgeDismisserDelegates {
if delegate.scrollView == scrollView {
return delegate
}
}
let delegate = ScrollViewTopEdgeDismisserDelegate()
delegate.scrollView = scrollView
scrollViewTopEdgeDismisserDelegates.append(delegate)
return delegate
}
@objc func gestureRecognizerDidChange(_ gestureRecognizer: UIGestureRecognizer) {
if gestureRecognizer.state == .began || gestureRecognizer.state == .recognized {
delegate?.dismiss()
}
}
weak var delegate: ViewControllerDismisserDelegate?
public var gestureRecognizers: Set<UIGestureRecognizer> {
set { gestureDelegate.gestureRecognizers = newValue }
get { return gestureDelegate.gestureRecognizers }
}
init(gestureDelegate: GestureDelegate) {
self.gestureDelegate = gestureDelegate
}
private var gestureDelegate: GestureDelegate
private var scrollViewTopEdgeDismisserDelegates: [ScrollViewTopEdgeDismisserDelegate] = []
}
private final class ScrollViewTopEdgeDismisserDelegate: NSObject, UIGestureRecognizerDelegate {
func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let pan = gestureRecognizer as? UIPanGestureRecognizer, let scrollView = scrollView {
return pan.translation(in: pan.view).y > 0
&& scrollView.contentOffset.y <= -scrollView.contentInset.top
}
return false
}
weak var scrollView: UIScrollView?
}
final class GestureDelegate: NSObject, UIGestureRecognizerDelegate {
var gestureRecognizers = Set<UIGestureRecognizer>()
var soloGestureRecognizers = Set<UIGestureRecognizer>()
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if soloGestureRecognizers.contains(gestureRecognizer) || soloGestureRecognizers.contains(otherGestureRecognizer) {
return false
}
return gestureRecognizers.contains(gestureRecognizer)
&& gestureRecognizers.contains(otherGestureRecognizer)
}
}
protocol ViewControllerDismisserDelegate: class {
func dismiss()
}
|
apache-2.0
|
52b5750fbbab1329b44e210bb0916632
| 35.956897 | 162 | 0.782599 | 5.553109 | false | false | false | false |
benjohnde/Caffeine
|
Caffeine/CaffeineController.swift
|
1
|
1121
|
//
// CaffeineController.swift
// Caffeine
//
// Created by Ben John on 10/12/15.
// Copyright © 2015 Ben John. All rights reserved.
//
import Cocoa
protocol CaffeineControllerDelegate {
func popUpStatusItemMenu()
}
class CaffeineController: CaffeineStatusItemDelegate {
fileprivate var delegate: CaffeineControllerDelegate
fileprivate var statusItem: CaffeineStatusItem?
fileprivate let caffeine: CaffeineInjector = CaffeineInjector()
init(delegate: CaffeineControllerDelegate, statusItem: NSStatusItem) {
self.delegate = delegate
self.statusItem = CaffeineStatusItem(delegate: self, statusItem: statusItem)
}
func shutdown() {
caffeine.release()
}
// MARK: - CaffeineStatusItemDelegate
func toggleInjection() {
if caffeine.status == CaffeineStatus.clean {
statusItem!.showInjectedStatusIcon()
caffeine.inject()
return
}
statusItem!.showCleanStatusIcon()
caffeine.release()
}
func popUpStatusItemMenu() {
delegate.popUpStatusItemMenu()
}
}
|
mit
|
6d232551642a2e522fb93172ce11e77d
| 25.046512 | 84 | 0.673214 | 4.609053 | false | false | false | false |
february29/Learning
|
swift/Fch_Contact/Pods/RxSwift/RxSwift/Observables/Optional.swift
|
24
|
3226
|
//
// Optional.swift
// RxSwift
//
// Created by tarunon on 2016/12/13.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Converts a optional to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter optional: Optional element in the resulting observable sequence.
- returns: An observable sequence containing the wrapped value or not from given optional.
*/
public static func from(optional: E?) -> Observable<E> {
return ObservableOptional(optional: optional)
}
/**
Converts a optional to an observable sequence.
- seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html)
- parameter optional: Optional element in the resulting observable sequence.
- parameter: Scheduler to send the optional element on.
- returns: An observable sequence containing the wrapped value or not from given optional.
*/
public static func from(optional: E?, scheduler: ImmediateSchedulerType) -> Observable<E> {
return ObservableOptionalScheduled(optional: optional, scheduler: scheduler)
}
}
final fileprivate class ObservableOptionalScheduledSink<O: ObserverType> : Sink<O> {
typealias E = O.E
typealias Parent = ObservableOptionalScheduled<E>
private let _parent: Parent
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
return _parent._scheduler.schedule(_parent._optional) { (optional: E?) -> Disposable in
if let next = optional {
self.forwardOn(.next(next))
return self._parent._scheduler.schedule(()) { _ in
self.forwardOn(.completed)
self.dispose()
return Disposables.create()
}
} else {
self.forwardOn(.completed)
self.dispose()
return Disposables.create()
}
}
}
}
final fileprivate class ObservableOptionalScheduled<E> : Producer<E> {
fileprivate let _optional: E?
fileprivate let _scheduler: ImmediateSchedulerType
init(optional: E?, scheduler: ImmediateSchedulerType) {
_optional = optional
_scheduler = scheduler
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == E {
let sink = ObservableOptionalScheduledSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
final fileprivate class ObservableOptional<E>: Producer<E> {
private let _optional: E?
init(optional: E?) {
_optional = optional
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == E {
if let element = _optional {
observer.on(.next(element))
}
observer.on(.completed)
return Disposables.create()
}
}
|
mit
|
febe1106345d185c851e44159a5cbc1a
| 32.947368 | 139 | 0.64124 | 4.735683 | false | false | false | false |
mabidakun/StringSearchKit
|
StringSearchKit/Classes/StringDictionary.swift
|
1
|
3571
|
//
// Created by Mike O. Abidakun 2017.
// Copyright (c) 2017-Present Mike O. Abidakun. All rights reserved.
//
// 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 class StringDictionary: StringDictionaryType {
private (set) var preservesCase = false
fileprivate let stringStore = Trie()
lazy var wordMap: [String : String] = {
return [:]
}()
// MARK:- Initialisers
public init(withStrings strings: [String], preserveCase: Bool = false) {
self.preservesCase = preserveCase
populate(with: strings)
}
public convenience init(withTextFileNamed filename: String, preserveCase: Bool = false) {
self.init(withStrings: StringLoader.load(fromTextFileNamed: filename), preserveCase: preserveCase)
}
public convenience init(withTextFilepath filepath: String, preserveCase: Bool = false) {
self.init(withStrings: StringLoader.load(withFilepath: filepath), preserveCase: preserveCase)
}
// MARK:- add
public func add(strings: [String]) {
stringStore.add(strings: strings)
}
public func add(string: String) {
stringStore.add(string: string)
}
public func contains(string: String) -> Bool {
return stringStore.contains(string: string)
}
public func strings(withPrefix prefix: String) -> [String] {
let results = stringStore.strings(withPrefix: prefix)
return preservesCase ? originalCaseWords(for: results) : results
}
}
// MARK: -
private extension StringDictionary {
func populate(with strings: [String]) {
strings.addEntries(to: stringStore)
if preservesCase {
wordMap = createWordMap(using: strings,
finder: stringStore.strings(withPrefix:))
}
}
func createWordMap(using words: [String], finder find: (String) -> [String]) -> [String: String] {
return words.reduce(into: [String: String]()) { (wordMap, originalWord) in
let matchedWords = find(originalWord)
let key = originalWord.lowercased()
if matchedWords.contains(key){
wordMap[key] = originalWord
}
}
}
func originalCaseWords(for words:[String]) -> [String] {
return words.map { [weak self] (word) -> String in
if let originalWord = self?.wordMap[word] {
return originalWord
}
return word
}
}
}
|
mit
|
67f1b4da8688298a9c510ffaa261979b
| 34.71 | 106 | 0.657519 | 4.425031 | false | false | false | false |
LiuSky/XBKit
|
Sources/Styles/SpacingPalette.swift
|
1
|
495
|
//
// SpacingPalette.swift
// XBKit
//
// Created by xiaobin liu on 2017/3/24.
// Copyright © 2017年 Sky. All rights reserved.
//
import Foundation
/// MARK - 间距模版
public struct SpacingPalette {
public static let h4 = 4
public static let h8 = 8
public static let h12 = 12
public static let h16 = 16
public static let h20 = 20
public static let h30 = 30
public static let h40 = 40
public static let h64 = 64
public static let h100 = 100
}
|
mit
|
ac9e5ca9fb3ec6cc454baced3a5fa6c7
| 20.043478 | 47 | 0.64876 | 3.432624 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureKYC/Sources/FeatureKYCUI/CountrySelector/KYCCountrySelectionInteractor.swift
|
1
|
1756
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import FeatureAuthenticationDomain
import NetworkKit
import PlatformKit
import RxSwift
import ToolKit
class KYCCountrySelectionInteractor {
private let jwtService: JWTServiceAPI
private let kycClient: KYCClientAPI
init(
jwtService: JWTServiceAPI = resolve(),
kycClient: KYCClientAPI = resolve()
) {
self.kycClient = kycClient
self.jwtService = jwtService
}
func selected(country: CountryData, shouldBeNotifiedWhenAvailable: Bool? = nil) -> Disposable {
sendSelection(countryCode: country.code, shouldBeNotifiedWhenAvailable: shouldBeNotifiedWhenAvailable)
}
func selected(state: KYCState, shouldBeNotifiedWhenAvailable: Bool? = nil) -> Disposable {
sendSelection(
countryCode: state.countryCode,
state: state.code,
shouldBeNotifiedWhenAvailable: shouldBeNotifiedWhenAvailable
)
}
private func sendSelection(
countryCode: String,
state: String? = nil,
shouldBeNotifiedWhenAvailable: Bool? = nil
) -> Disposable {
jwtService.token
.asObservable()
.take(1)
.asSingle()
.flatMapCompletable(weak: self) { (self, jwtToken) -> Completable in
self.kycClient.selectCountry(
country: countryCode,
state: state,
notifyWhenAvailable: shouldBeNotifiedWhenAvailable ?? false,
jwtToken: jwtToken
)
.asObservable()
.ignoreElements()
.asCompletable()
}
.subscribe()
}
}
|
lgpl-3.0
|
3cb7c4a69f889da92ff7bdc6c84ade71
| 29.258621 | 110 | 0.618234 | 5.207715 | false | false | false | false |
vector-im/riot-ios
|
Riot/Modules/ServiceTerms/Modal/Modal/ServiceTermsModalScreenCoordinator.swift
|
1
|
2984
|
// File created from ScreenTemplate
// $ createScreen.sh Modal/Show ServiceTermsModalScreen
/*
Copyright 2019 New Vector 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 Foundation
import UIKit
final class ServiceTermsModalScreenCoordinator: ServiceTermsModalScreenCoordinatorType {
// MARK: - Properties
// MARK: Private
private var serviceTermsModalScreenViewModel: ServiceTermsModalScreenViewModelType
private let serviceTermsModalScreenViewController: ServiceTermsModalScreenViewController
// Must be used only internally
var childCoordinators: [Coordinator] = []
// MARK: Public
weak var delegate: ServiceTermsModalScreenCoordinatorDelegate?
// MARK: - Setup
init(serviceTerms: MXServiceTerms, outOfContext: Bool = false) {
let serviceTermsModalScreenViewModel = ServiceTermsModalScreenViewModel(serviceTerms: serviceTerms, outOfContext: outOfContext)
let serviceTermsModalScreenViewController = ServiceTermsModalScreenViewController.instantiate(with: serviceTermsModalScreenViewModel)
self.serviceTermsModalScreenViewModel = serviceTermsModalScreenViewModel
self.serviceTermsModalScreenViewController = serviceTermsModalScreenViewController
}
// MARK: - Public methods
func start() {
self.serviceTermsModalScreenViewModel.coordinatorDelegate = self
}
func toPresentable() -> UIViewController {
return self.serviceTermsModalScreenViewController
}
}
// MARK: - ServiceTermsModalScreenViewModelCoordinatorDelegate
extension ServiceTermsModalScreenCoordinator: ServiceTermsModalScreenViewModelCoordinatorDelegate {
func serviceTermsModalScreenViewModelDidAccept(_ viewModel: ServiceTermsModalScreenViewModelType) {
self.delegate?.serviceTermsModalScreenCoordinatorDidAccept(self)
}
func serviceTermsModalScreenViewModel(_ coordinator: ServiceTermsModalScreenViewModelType, displayPolicy policy: MXLoginPolicyData) {
self.delegate?.serviceTermsModalScreenCoordinator(self, displayPolicy: policy)
}
func serviceTermsModalScreenViewModelDidDecline(_ viewModel: ServiceTermsModalScreenViewModelType) {
self.delegate?.serviceTermsModalScreenCoordinatorDidDecline(self)
}
func serviceTermsModalScreenViewModelDidCancel(_ viewModel: ServiceTermsModalScreenViewModelType) {
self.delegate?.serviceTermsModalScreenCoordinatorDidCancel(self)
}
}
|
apache-2.0
|
acdfe70e13c46446fe0c69f289275b49
| 37.753247 | 141 | 0.780831 | 6.114754 | false | false | false | false |
jeden/wormer
|
wormer/Worming.playground/Contents.swift
|
1
|
1421
|
//: Playground - noun: a place where people can play
import UIKit
import Wormer
protocol EventBus{}
class EventBusImplementation:EventBus{}
protocol NotificationGateway{}
class NotificationGatewayImplementation:NotificationGateway{ init(eventBus: EventBus){}}
protocol NearableProximityProvider {}
struct BrandedNearableProximityProvider : NearableProximityProvider {}
do {
let injector = Injector.default
/// 1
injector.bind(interface: EventBus.self,
toImplementation: EventBusImplementation.self, asSingleton: true) {
EventBusImplementation()
}
let eventBus: EventBus = injector.instance()
/// 2
injector.bind(interface: NotificationGateway.self,
toImplementation: NotificationGatewayImplementation.self, asSingleton: true) {
NotificationGatewayImplementation(eventBus: eventBus)
}
/// 3
injector.bind(interface: NearableProximityProvider.self,
toImplementation: BrandedNearableProximityProvider.self, asSingleton: false) {
BrandedNearableProximityProvider()
}
}
struct SomeProvider {
private var eventBus: EventBus
init(eventBus: EventBus) {
self.eventBus = eventBus
}
}
let eventBus: EventBus = Injector.default.instance()
let provider = SomeProvider(eventBus: eventBus)
class EventViewController : UIViewController /* NSViewController */ {
private lazy var eventBus: EventBus = Injector.default.instance()
}
EventViewController()
|
mit
|
c6d91fde531832604dc973813d0c7227
| 27.44 | 93 | 0.76988 | 4.319149 | false | false | false | false |
jjjjaren/jCode
|
jCode/Classes/Utilities/XCDirectory.swift
|
1
|
1579
|
//
// XCDirectory.swift
// jCode
//
// Created by Jaren Hamblin on 11/6/17.
//
import Foundation
///
public class XCDirectory {
///
public static func directoryURL(for searchDirectory: FileManager.SearchPathDirectory) -> URL {
let urls = FileManager.default.urls(for: searchDirectory, in: FileManager.SearchPathDomainMask.userDomainMask)
return urls[urls.count-1]
}
///
public static func createIntermediateDirectories(url: URL) {
let fileManager: FileManager = FileManager.default
if !fileManager.fileExists(atPath: url.absoluteString, isDirectory: nil) {
try! fileManager.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
}
}
///
public static let document: URL = directoryURL(for: FileManager.SearchPathDirectory.documentDirectory)
///
public static let library: URL = directoryURL(for: FileManager.SearchPathDirectory.libraryDirectory)
///
public static let applicationSupport: URL = directoryURL(for: FileManager.SearchPathDirectory.applicationSupportDirectory)
///
public static let caches: URL = directoryURL(for: FileManager.SearchPathDirectory.cachesDirectory)
///
private let fileManager: FileManager
///
@available(iOS 10.0, *)
public var temporary: URL { return FileManager.default.temporaryDirectory }
///
public init(fileManager: FileManager = FileManager.default) {
self.fileManager = fileManager
}
}
public typealias XCDir = XCDirectory
|
mit
|
73ccb382f2a8851c6cb6eb225994c223
| 29.365385 | 126 | 0.693477 | 5.028662 | false | false | false | false |
vhbit/MastodonKit
|
Sources/MastodonKit/Models/ClientApplication.swift
|
1
|
886
|
import Foundation
public struct ClientApplication {
/// The application ID.
public let id: Int
/// Where the user should be redirected after authorization.
public let redirectURI: String
/// The application client ID.
public let clientID: String
/// The application client secret.
public let clientSecret: String
}
extension ClientApplication {
init?(from dictionary: JSONDictionary) {
guard
let id = dictionary["id"] as? Int,
let redirectURI = dictionary["redirect_uri"] as? String,
let clientID = dictionary["client_id"] as? String,
let clientSecret = dictionary["client_secret"] as? String
else {
return nil
}
self.id = id
self.redirectURI = redirectURI
self.clientID = clientID
self.clientSecret = clientSecret
}
}
|
mit
|
4cb510634f3a08c183b4144a491e88b3
| 28.533333 | 69 | 0.623025 | 5.121387 | false | false | false | false |
justinhester/hacking-with-swift
|
src/Project20/Project20/GameViewController.swift
|
1
|
1644
|
//
// GameViewController.swift
// Project20
//
// Created by Justin Lawrence Hester on 2/12/16.
// Copyright (c) 2016 Justin Lawrence Hester. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func motionBegan(motion: UIEventSubtype, withEvent event: UIEvent?) {
let skView = view as! SKView
let gameScene = skView.scene as! GameScene
gameScene.explodeFireworks()
}
}
|
gpl-3.0
|
4225d77be2418a90ba6eb3d175e5c8c1
| 26.864407 | 94 | 0.615572 | 5.498328 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceApplication/Tests/EurofurenceApplicationTests/Application/Components/Announcements/Presenter Tests/Test Doubles/CapturingAnnouncementsScene.swift
|
1
|
887
|
import EurofurenceApplication
import EurofurenceModel
import UIKit
class CapturingAnnouncementsScene: UIViewController, AnnouncementsScene {
private(set) var delegate: AnnouncementsSceneDelegate?
func setDelegate(_ delegate: AnnouncementsSceneDelegate) {
self.delegate = delegate
}
private(set) var capturedTitle: String?
func setAnnouncementsTitle(_ title: String) {
capturedTitle = title
}
private(set) var capturedAnnouncementsToBind: Int?
private(set) var binder: AnnouncementsBinder?
func bind(numberOfAnnouncements: Int, using binder: AnnouncementsBinder) {
capturedAnnouncementsToBind = numberOfAnnouncements
self.binder = binder
}
private(set) var capturedAnnouncementIndexToDeselect: Int?
func deselectAnnouncement(at index: Int) {
capturedAnnouncementIndexToDeselect = index
}
}
|
mit
|
697e791b3dc234a294434462623a5bbc
| 29.586207 | 78 | 0.745209 | 5.248521 | false | false | false | false |
scotlandyard/expocity
|
expocity/Controller/Home/CHome.swift
|
1
|
2030
|
import UIKit
class CHome:CController
{
weak var viewHome:VHome!
let model:MHome
init()
{
model = MHome()
super.init(nibName:nil, bundle:nil)
}
required init?(coder:NSCoder)
{
fatalError()
}
override func viewDidLoad()
{
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector:#selector(notifiedSessionLoaded(sender:)),
name:Notification.Notifications.sessionLoaded.Value,
object:nil)
MSession.sharedInstance.load()
}
override func loadView()
{
let viewHome:VHome = VHome(controller:self)
self.viewHome = viewHome
view = viewHome
}
//MARK: notified
func notifiedSessionLoaded(sender notification:Notification)
{
DispatchQueue.main.async
{ [weak self] in
self?.viewHome.stopLoading()
}
}
//MARK: private
private func createFirebaseRoom()
{
let firebaseRoom:FDatabaseModelRoom = model.room()
let json:Any = firebaseRoom.modelJson()
let path:String = FDatabase.Parent.room.rawValue
let roomId:String = FMain.sharedInstance.database.createChild(
path:path,
json:json)
MSession.sharedInstance.createdRoom(roomId:roomId)
DispatchQueue.main.async
{ [weak self] in
self?.firebaseRoomCreated(roomId:roomId)
}
}
private func firebaseRoomCreated(roomId:String)
{
viewHome.stopLoading()
let chat:CChat = CChat(roomId:roomId)
parentController.push(controller:chat)
}
//MARK: public
func createChat()
{
viewHome.startLoading()
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.createFirebaseRoom()
}
}
}
|
mit
|
db589b4cd264fdaaad47eaefcb86ae87
| 21.555556 | 71 | 0.563547 | 4.95122 | false | false | false | false |
tskulbru/DropDown
|
DropDown/helpers/UIView+Extension.swift
|
1
|
1412
|
//
// UIView+Constraints.swift
// DropDown
//
// Created by Kevin Hirsch on 28/07/15.
// Copyright (c) 2015 Kevin Hirsch. All rights reserved.
//
import UIKit
//MARK: - Constraints
internal extension UIView {
func addConstraints(#format: String, options: NSLayoutFormatOptions = nil, metrics: [NSObject: AnyObject]? = nil, views: [String: UIView]) {
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat(format, options: options, metrics: metrics, views: views))
}
func addUniversalConstraints(#format: String, options: NSLayoutFormatOptions = nil, metrics: [NSObject: AnyObject]? = nil, views: [String: UIView]) {
addConstraints(format: "H:\(format)", options: options, metrics: metrics, views: views)
addConstraints(format: "V:\(format)", options: options, metrics: metrics, views: views)
}
}
//MARK: - Bounds
internal extension UIView {
var windowFrame: CGRect? {
return superview?.convertRect(frame, toView: nil)
}
}
internal extension UIWindow {
static func visibleWindow() -> UIWindow? {
var currentWindow = UIApplication.sharedApplication().keyWindow
if currentWindow == nil {
let frontToBackWindows = UIApplication.sharedApplication().windows.reverse() as! [UIWindow]
for window in frontToBackWindows {
if window.windowLevel == UIWindowLevelNormal {
currentWindow = window
break
}
}
}
return currentWindow
}
}
|
mit
|
80b8e5ccda34ac7a9e8079901b149e86
| 23.789474 | 150 | 0.713881 | 4.057471 | false | false | false | false |
enstulen/ARKitAnimation
|
Pods/SwiftCharts/SwiftCharts/Axis/ChartAxisLabelsGeneratorNumber.swift
|
1
|
1135
|
//
// ChartAxisLabelsGeneratorNumber.swift
// SwiftCharts
//
// Created by ischuetz on 27/06/16.
// Copyright © 2016 ivanschuetz. All rights reserved.
//
import Foundation
/// Generates a single formatted number for scalar
open class ChartAxisLabelsGeneratorNumber: ChartAxisLabelsGeneratorBase {
open let labelSettings: ChartLabelSettings
open let formatter: NumberFormatter
public init(labelSettings: ChartLabelSettings, formatter: NumberFormatter = ChartAxisLabelsGeneratorNumber.defaultFormatter) {
self.labelSettings = labelSettings
self.formatter = formatter
}
open override func generate(_ scalar: Double) -> [ChartAxisLabel] {
let text = formatter.string(from: NSNumber(value: scalar))!
return [ChartAxisLabel(text: text, settings: labelSettings)]
}
public static var defaultFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
return formatter
}()
open override func fonts(_ scalar: Double) -> [UIFont] {
return [labelSettings.font]
}
}
|
mit
|
34a39410c676abce3bfcb8003a5ec08f
| 29.648649 | 130 | 0.698413 | 5.349057 | false | false | false | false |
DarielChen/DemoCode
|
iOS动画指南/iOS动画指南 - 3.Layer Animations的进阶使用/2.ShapeMask/ShapeMask/ViewController.swift
|
1
|
2081
|
//
// ViewController.swift
// ShapeMask
//
// Created by Dariel on 16/6/21.
// Copyright © 2016年 Dariel. All rights reserved.
//
import UIKit
func delay(seconds seconds: Double, completion:()->()) {
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64( Double(NSEC_PER_SEC) * seconds ))
dispatch_after(popTime, dispatch_get_main_queue()) {
completion()
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
avatar1.image = UIImage(named: "avatar-1")
avatar2.image = UIImage(named: "avatar-2")
avatar1.label.text = "FOX"
avatar2.label.text = "DOG"
view.addSubview(avatar1)
view.addSubview(avatar2)
view.backgroundColor = UIColor(red: 130/255.0, green: 209/255.0, blue: 93/255.0, alpha: 1)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let avatarSize = avatar1.frame.size
let morphSize = CGSize(
width: avatarSize.width * 0.85,
height: avatarSize.height * 1.05)
let bounceXOffset: CGFloat = view.frame.size.width/2.0 - avatar1.lineWidth*2 - avatar1.frame.width
avatar2.boundsOffset(bounceXOffset, morphSize:morphSize)
avatar1.boundsOffset(avatar1.frame.origin.x - bounceXOffset, morphSize:morphSize)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
lazy var avatar1: AvatarView = {
let avatarView = AvatarView()
// avatarView.backgroundColor = UIColor.redColor()
avatarView.frame = CGRect(x: self.view.frame.width-90-20, y: self.view.center.y, width: 90, height: 90)
return avatarView
}()
lazy var avatar2: AvatarView = {
let avatarView = AvatarView()
avatarView.frame = CGRect(x: 20, y: self.view.center.y, width: 90, height: 90)
// avatarView.backgroundColor = UIColor.orangeColor()
return avatarView
}()
}
|
mit
|
8468adf8d20052dc82635c5b5b57716e
| 27.465753 | 111 | 0.619346 | 4.042802 | false | false | false | false |
trident10/TDMediaPicker
|
TDMediaPicker/Classes/View/CustomCell/TDMediaCell.swift
|
1
|
3857
|
//
// TDMediaCell.swift
// ImagePicker
//
// Created by Abhimanu Jindal on 03/07/17.
// Copyright © 2017 Abhimanu Jindal. All rights reserved.
//
import UIKit
import Photos
class TDMediaCell: UICollectionViewCell{
// MARK: - Variable
@IBOutlet var imageView: UIImageView!
enum CellType{
case Image, ImageThumb, Video, VideoThumb
}
enum ButtonType{
case videoPlay
}
// MARK: - Initialization
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super .init(coder: aDecoder)
}
static func mediaCellWithType(_ type: TDMediaCell.CellType, collectionView: UICollectionView, for indexPath: IndexPath) -> TDMediaCell{
switch type {
case .Image:
return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: TDMediaCellImage.self), for: indexPath) as! TDMediaCell
case .ImageThumb:
return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: TDMediaCellImageThumb.self), for: indexPath) as! TDMediaCell
case .Video:
return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: TDMediaCellVideo.self), for: indexPath) as! TDMediaCell
case .VideoThumb:
return collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: TDMediaCellVideoThumb.self), for: indexPath) as! TDMediaCell
}
}
static func registerCellWithType(_ type: TDMediaCell.CellType, collectionView: UICollectionView){
switch type {
case .Image:
collectionView.register(UINib.init(nibName: String(describing: TDMediaCellImage.self), bundle: TDMediaUtil.xibBundle()), forCellWithReuseIdentifier: String(describing: TDMediaCellImage.self))
case .ImageThumb:
collectionView.register(UINib.init(nibName: String(describing: TDMediaCellImageThumb.self), bundle: TDMediaUtil.xibBundle()), forCellWithReuseIdentifier: String(describing: TDMediaCellImageThumb.self))
case .Video:
collectionView.register(UINib.init(nibName: String(describing: TDMediaCellVideo.self), bundle: TDMediaUtil.xibBundle()), forCellWithReuseIdentifier: String(describing: TDMediaCellVideo.self))
case .VideoThumb:
collectionView.register(UINib.init(nibName: String(describing: TDMediaCellVideoThumb.self), bundle: TDMediaUtil.xibBundle()), forCellWithReuseIdentifier: String(describing: TDMediaCellVideoThumb.self))
}
}
func onButtonTap(handler: ((_ type: TDMediaCell.ButtonType)->Void)?){
fatalError("This should be implemented by concrete class")
}
func configure(_ asset: PHAsset, completionHandler: ((_ image: UIImage)->Void)?) {
imageView.layoutIfNeeded()
_ = TDMediaUtil.fetchImage(asset, targetSize: self.frame.size, completionHandler: { (image, error) in
if image != nil{
self.imageView.image = image
if TDMediaUtil.isImageResolutionValid(self.imageView, image: image!){
completionHandler?(image!)
}
}
})
}
func configure(_ image: UIImage) {
imageView.layoutIfNeeded()
imageView.image = image
}
func willInitiateDisplay(){
fatalError("This should be implemented by concrete class")
}
func didEndDisplay(){
fatalError("This should be implemented by concrete class")
}
func processHighlighting(shouldDisplay: Bool, count: Int = -1, text: String = ""){
fatalError("This should be implemented by concrete class")
}
}
|
mit
|
94b088e6643cc80876a35bfe9658afec
| 36.803922 | 213 | 0.656898 | 5.15508 | false | false | false | false |
00buggy00/SwiftOpenGLTutorials
|
11 OpenGLMVCPt1/SwiftOpenGLObjects.swift
|
1
|
6939
|
//
// SwiftOpenGLObjects.swift
// OpenGLMVCPt1
//
// Created by Myles Schultz on 1/27/18.
// Copyright © 2018 MyKo. All rights reserved.
//
import Foundation
import Quartz
protocol OpenGLObject {
var id: GLuint { get set }
func bind()
func unbind()
mutating func delete()
}
struct Vertex {
var position: Float3
var normal: Float3
var textureCoordinate: Float2
var color: Float3
}
struct VertexBufferObject: OpenGLObject {
var id: GLuint = 0
let type: GLenum = GLenum(GL_ARRAY_BUFFER)
var vertexCount: Int32 {
return Int32(data.count)
}
var data: [Vertex] = []
mutating func load(_ data: [Vertex]) {
self.data = data
glGenBuffers(1, &id)
bind()
glBufferData(GLenum(GL_ARRAY_BUFFER), data.count * MemoryLayout<Vertex>.size, data, GLenum(GL_STATIC_DRAW))
}
func bind() {
glBindBuffer(type, id)
}
func unbind() {
glBindBuffer(type, id)
}
mutating func delete() {
glDeleteBuffers(1, &id)
}
}
struct VertexArrayObject: OpenGLObject {
var id: GLuint = 0
mutating func layoutVertexPattern() {
glGenVertexArrays(1, &id)
bind()
/* Position */
glVertexAttribPointer(0, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 0))
glEnableVertexAttribArray(0)
/* Normal */
glVertexAttribPointer(1, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 12))
glEnableVertexAttribArray(1)
/* Texture Coordinate */
glVertexAttribPointer(2, 2, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern: 24))
glEnableVertexAttribArray(2)
/* Color */
glVertexAttribPointer(3, 3, GLenum(GL_FLOAT), GLboolean(GL_FALSE), 44, UnsafePointer<GLuint>(bitPattern:32))
glEnableVertexAttribArray(3)
}
func bind() {
glBindVertexArray(id)
}
func unbind() {
glBindVertexArray(id)
}
mutating func delete() {
glDeleteVertexArrays(1, &id)
}
}
enum TextureSlot: GLint {
case texture1 = 33984
}
struct TextureBufferObject: OpenGLObject {
var id: GLuint = 0
var textureSlot: GLint = TextureSlot.texture1.rawValue
mutating func loadTexture(named name: String) {
guard let textureData = NSImage(named: NSImage.Name(rawValue: name))?.tiffRepresentation else {
Swift.print("Image name not located in Image Asset Catalog")
return
}
glGenTextures(1, &id)
bind()
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MIN_FILTER), GL_LINEAR)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_MAG_FILTER), GL_LINEAR)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_S), GL_REPEAT)
glTexParameteri(GLenum(GL_TEXTURE_2D), GLenum(GL_TEXTURE_WRAP_T), GL_REPEAT)
glTexImage2D(GLenum(GL_TEXTURE_2D), 0, GL_RGBA, 256, 256, 0, GLenum(GL_RGBA), GLenum(GL_UNSIGNED_BYTE), (textureData as NSData).bytes)
}
func bind() {
glBindTexture(GLenum(GL_TEXTURE_2D), id)
}
func unbind() {
glBindTexture(GLenum(GL_TEXTURE_2D), 0)
}
mutating func delete() {
glDeleteTextures(1, &id)
}
}
enum ShaderType: UInt32 {
case vertex = 35633 /* GL_VERTEX_SHADER */
case fragment = 35632 /* GL_FRAGMENT_SHADER */
}
struct Shader: OpenGLObject {
var id: GLuint = 0
mutating func create(withVertex vertexSource: String, andFragment fragmentSource: String) {
id = glCreateProgram()
let vertex = compile(shaderType: .vertex, withSource: vertexSource)
let fragment = compile(shaderType: .fragment, withSource: fragmentSource)
link(vertexShader: vertex, fragmentShader: fragment)
}
func compile(shaderType type: ShaderType, withSource source: String) -> GLuint {
let shader = glCreateShader(type.rawValue)
var pointerToShader = UnsafePointer<GLchar>(source.cString(using: String.Encoding.ascii))
glShaderSource(shader, 1, &pointerToShader, nil)
glCompileShader(shader)
var compiled: GLint = 0
glGetShaderiv(shader, GLbitfield(GL_COMPILE_STATUS), &compiled)
if compiled <= 0 {
print("Could not compile shader type: \(type), getting log...")
var logLength: GLint = 0
print("Log length: \(logLength)")
glGetShaderiv(shader, GLenum(GL_INFO_LOG_LENGTH), &logLength)
if logLength > 0 {
let cLog = UnsafeMutablePointer<CChar>.allocate(capacity: Int(logLength))
glGetShaderInfoLog(shader, GLsizei(logLength), &logLength, cLog)
print("\n\t\(String.init(cString: cLog))")
free(cLog)
}
}
return shader
}
func link(vertexShader vertex: GLuint, fragmentShader fragment: GLuint) {
glAttachShader(id, vertex)
glAttachShader(id, fragment)
glLinkProgram(id)
var linked: GLint = 0
glGetProgramiv(id, UInt32(GL_LINK_STATUS), &linked)
if linked <= 0 {
print("Could not link, getting log")
var logLength: GLint = 0
glGetProgramiv(id, UInt32(GL_INFO_LOG_LENGTH), &logLength)
print(" logLength = \(logLength)")
if logLength > 0 {
let cLog = UnsafeMutablePointer<CChar>.allocate(capacity: Int(logLength))
glGetProgramInfoLog(id, GLsizei(logLength), &logLength, cLog)
print("log: \(String.init(cString:cLog))")
free(cLog)
}
}
glDeleteShader(vertex)
glDeleteShader(fragment)
}
func setInitialUniforms() {
let location = glGetUniformLocation(id, "sample")
glUniform1i(location, GLint(GL_TEXTURE0))
bind()
glUniform3fv(glGetUniformLocation(id, "light.color"), 1, [1.0, 1.0, 1.0])
glUniform3fv(glGetUniformLocation(id, "light.position"), 1, [0.0, 2.0, 2.0])
glUniform1f(glGetUniformLocation(id, "light.ambient"), 0.25)
glUniform1f(glGetUniformLocation(id, "light.specStrength"), 3.0)
glUniform1f(glGetUniformLocation(id, "light.specHardness"), 32)
}
func update(view: FloatMatrix4, projection: FloatMatrix4) {
glUniformMatrix4fv(glGetUniformLocation(id, "view"), 1, GLboolean(GL_FALSE), view.columnMajorArray())
glUniformMatrix4fv(glGetUniformLocation(id, "projection"), 1, GLboolean(GL_FALSE), projection.columnMajorArray())
}
func bind() {
glUseProgram(id)
}
func unbind() {
glUseProgram(0)
}
func delete() {
glDeleteProgram(id)
}
}
|
mit
|
81df41421170754027346d1ba45d13b2
| 31.57277 | 142 | 0.612136 | 4.054939 | false | false | false | false |
zisko/swift
|
test/SILGen/switch_var.swift
|
1
|
28381
|
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func runced(x x: Int) -> Bool { return true }
func funged(x x: Int) -> Bool { return true }
func ansed(x x: Int) -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func foos() -> String { return "" }
func bars() -> String { return "" }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(x x: Int) {}
func b(x x: Int) {}
func c(x x: Int) {}
func d(x x: Int) {}
func a(x x: String) {}
func b(x x: String) {}
func aa(x x: (Int, Int)) {}
func bb(x x: (Int, Int)) {}
func cc(x x: (Int, Int)) {}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_1yyF
func test_var_1() {
// CHECK: function_ref @$S10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK-NOT: br bb
case var x:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$S10switch_var1byyF
b()
}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_2yyF
func test_var_2() {
// CHECK: function_ref @$S10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// -- TODO: Clean up these empty waypoint bbs.
case var x where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case var y where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: br [[CASE3:bb[0-9]+]]
case var z:
// CHECK: [[CASE3]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CONT]]
c(x: z)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$S10switch_var1dyyF
d()
}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_3yyF
func test_var_3() {
// CHECK: function_ref @$S10switch_var3fooSiyF
// CHECK: function_ref @$S10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$S10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var2aa1xySi_Sit_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
aa(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: br [[NO_CASE1_TARGET:bb[0-9]+]]
// CHECK: [[NO_CASE1_TARGET]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1a1xySi_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1b1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
a(x: y)
b(x: z)
// CHECK: [[NO_CASE2]]:
// CHECK: [[WADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$S10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case var w where ansed(x: w.0):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var2bb1xySi_Sit_tF
// CHECK: br [[CONT]]
bb(x: w)
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[CASE4:bb[0-9]+]]
case var v:
// CHECK: [[CASE4]]:
// CHECK: [[VADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%.*]] = project_box [[VADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[V]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var2cc1xySi_Sit_tF
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[CONT]]
cc(x: v)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$S10switch_var1dyyF
d()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_41pyAA1P_p_tF
func test_var_4(p p: P) {
// CHECK: function_ref @$S10switch_var3fooSiyF
switch (p, foo()) {
// CHECK: [[PAIR:%.*]] = alloc_stack $(P, Int)
// CHECK: store
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[T0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 1
// CHECK: [[PAIR_1:%.*]] = load [trivial] [[T0]] : $*Int
// CHECK: [[TMP:%.*]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to X in [[TMP]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*X
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[X]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case (is X, var x) where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: function_ref @$S10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[TMP:%.*]] = alloc_stack $Y
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to Y in [[TMP]] : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*Y
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[Y]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (is Y, var y) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var (P, Int) }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$S10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]]
case var z where ansed(x: z.1):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$S10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
c(x: z.1)
// CHECK: [[DFLT_NO_CASE3]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CASE4:bb[0-9]+]]
case (_, var w):
// CHECK: [[CASE4]]:
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[WADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1d1xySi_tF
// CHECK: destroy_value [[WADDR]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
d(x: w)
}
e()
}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_5yyF : $@convention(thin) () -> () {
func test_var_5() {
// CHECK: function_ref @$S10switch_var3fooSiyF
// CHECK: function_ref @$S10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b()
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case (_, _) where runced():
// CHECK: [[CASE3]]:
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: br [[CASE4:bb[0-9]+]]
case _:
// CHECK: [[CASE4]]:
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
e()
}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B7_returnyyF : $@convention(thin) () -> () {
func test_var_return() {
switch (foo(), bar()) {
case var x where runced():
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%[0-9]+]] = project_box [[XADDR]]
// CHECK: function_ref @$S10switch_var1ayyF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[EPILOG:bb[0-9]+]]
a()
return
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
case (var y, var z) where funged():
// CHECK: function_ref @$S10switch_var1byyF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[EPILOG]]
b()
return
case var w where ansed():
// CHECK: [[WADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%[0-9]+]] = project_box [[WADDR]]
// CHECK: function_ref @$S10switch_var1cyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[EPILOG]]
c()
return
case var v:
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%[0-9]+]] = project_box [[VADDR]]
// CHECK: function_ref @$S10switch_var1dyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[EPILOG]]
d()
return
}
}
// When all of the bindings in a column are immutable, don't emit a mutable
// box. <rdar://problem/15873365>
// CHECK-LABEL: sil hidden @$S10switch_var8test_letyyF : $@convention(thin) () -> () {
func test_let() {
// CHECK: [[FOOS:%.*]] = function_ref @$S10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @$S10switch_var6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
switch foos() {
case let x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: [[A:%.*]] = function_ref @$S10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[VAL_COPY_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[TRY_CASE2:bb[0-9]+]]
// CHECK: [[TRY_CASE2]]:
// CHECK: [[VAL_COPY_2:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @$S10switch_var6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY_2:%.*]] = begin_borrow [[VAL_COPY_2]]
// CHECK: [[VAL_COPY_2_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY_2]]
// CHECK: [[B:%.*]] = function_ref @$S10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[VAL_COPY_2_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY_2]] from [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: br [[NEXT_CASE:bb6]]
// CHECK: [[NEXT_CASE]]:
// CHECK: [[VAL_COPY_3:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @$S10switch_var4barsSSyF
// CHECK: [[BORROWED_VAL_COPY_3:%.*]] = begin_borrow [[VAL_COPY_3]]
// CHECK: [[VAL_COPY_3_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY_3]]
// CHECK: store [[VAL_COPY_3_COPY]] to [init] [[IN_ARG:%.*]] :
// CHECK: apply {{%.*}}<String>({{.*}}, [[IN_ARG]])
// CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// ExprPatterns implicitly contain a 'let' binding.
case bars():
// CHECK: [[YES_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: destroy_value [[VAL]]
// CHECK: function_ref @$S10switch_var1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: br [[NEXT_CASE:bb9+]]
// CHECK: [[NEXT_CASE]]:
case _:
// CHECK: destroy_value [[VAL]]
// CHECK: function_ref @$S10switch_var1dyyF
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$S10switch_var8test_letyyF'
// If one of the bindings is a "var", allocate a box for the column.
// CHECK-LABEL: sil hidden @$S10switch_var015test_mixed_let_B0yyF : $@convention(thin) () -> () {
func test_mixed_let_var() {
// CHECK: bb0:
// CHECK: [[FOOS:%.*]] = function_ref @$S10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
switch foos() {
// First pattern.
// CHECK: [[BOX:%.*]] = alloc_box ${ var String }, var, name "x"
// CHECK: [[PBOX:%.*]] = project_box [[BOX]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: store [[VAL_COPY]] to [init] [[PBOX]]
// CHECK: cond_br {{.*}}, [[CASE1:bb[0-9]+]], [[NOCASE1:bb[0-9]+]]
case var x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOX]]
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[A:%.*]] = function_ref @$S10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[X]])
// CHECK: destroy_value [[BOX]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NOCASE1]]:
// CHECK: destroy_value [[BOX]]
// CHECK: br [[NEXT_PATTERN:bb[0-9]+]]
// CHECK: [[NEXT_PATTERN]]:
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: cond_br {{.*}}, [[CASE2:bb[0-9]+]], [[NOCASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: [[B:%.*]] = function_ref @$S10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[VAL_COPY_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NOCASE2]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[NEXT_CASE]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[VAL_COPY_COPY:%.*]] = copy_value [[BORROWED_VAL_COPY]]
// CHECK: store [[VAL_COPY_COPY]] to [init] [[TMP_VAL_COPY_ADDR:%.*]] : $*String
// CHECK: apply {{.*}}<String>({{.*}}, [[TMP_VAL_COPY_ADDR]])
// CHECK: cond_br {{.*}}, [[CASE3:bb[0-9]+]], [[NOCASE3:bb[0-9]+]]
case bars():
// CHECK: [[CASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: [[FUNC:%.*]] = function_ref @$S10switch_var1cyyF : $@convention(thin) () -> ()
// CHECK: apply [[FUNC]]()
// CHECK: br [[CONT]]
c()
// CHECK: [[NOCASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[NEXT_CASE]]:
// CHECK: destroy_value [[VAL]]
// CHECK: [[D_FUNC:%.*]] = function_ref @$S10switch_var1dyyF : $@convention(thin) () -> ()
// CHECK: apply [[D_FUNC]]()
// CHECK: br [[CONT]]
case _:
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$S10switch_var015test_mixed_let_B0yyF'
// CHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns1yyF : $@convention(thin) () -> () {
func test_multiple_patterns1() {
// CHECK: function_ref @$S10switch_var6foobarSi_SityF
switch foobar() {
// CHECK-NOT: br bb
case (0, let x), (let x, 0):
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: debug_value [[FIRST_X:%.*]] :
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: debug_value [[SECOND_X:%.*]] :
// CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @$S10switch_var1a1xySi_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @$S10switch_var1byyF
b()
}
}
// FIXME(integers): the following checks should be updated for the new integer
// protocols. <rdar://problem/29939484>
// XCHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns2yyF : $@convention(thin) () -> () {
func test_multiple_patterns2() {
let t1 = 2
let t2 = 4
// XCHECK: debug_value [[T1:%.*]] :
// XCHECK: debug_value [[T2:%.*]] :
switch (0,0) {
// XCHECK-NOT: br bb
case (_, let x) where x > t1, (let x, _) where x > t2:
// XCHECK: [[FIRST_X:%.*]] = tuple_extract {{%.*}} : $(Int, Int), 1
// XCHECK: debug_value [[FIRST_X]] :
// XCHECK: apply {{%.*}}([[FIRST_X]], [[T1]])
// XCHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// XCHECK: [[FIRST_MATCH_CASE]]:
// XCHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// XCHECK: [[FIRST_FAIL]]:
// XCHECK: debug_value [[SECOND_X:%.*]] :
// XCHECK: apply {{%.*}}([[SECOND_X]], [[T2]])
// XCHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// XCHECK: [[SECOND_MATCH_CASE]]:
// XCHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// XCHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// XCHECK: [[A:%.*]] = function_ref @$S10switch_var1aySi1x_tF
// XCHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// XCHECK: [[SECOND_FAIL]]:
// XCHECK: function_ref @$S10switch_var1byyF
b()
}
}
enum Foo {
case A(Int, Double)
case B(Double, Int)
case C(Int, Int, Double)
}
// CHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns3yyF : $@convention(thin) () -> () {
func test_multiple_patterns3() {
let f = Foo.C(0, 1, 2.0)
switch f {
// CHECK: switch_enum {{%.*}} : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
case .A(let x, let n), .B(let n, let x), .C(_, let x, let n):
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int, [[A_N]] : $Double)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int, [[B_N]] : $Double)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: [[C__:%.*]] = tuple_extract
// CHECK: [[C_X:%.*]] = tuple_extract
// CHECK: [[C_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double):
// CHECK: [[FUNC_A:%.*]] = function_ref @$S10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
enum Bar {
case Y(Foo, Int)
case Z(Int, Foo)
}
// CHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns4yyF : $@convention(thin) () -> () {
func test_multiple_patterns4() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(let x, _), _), .Y(.B(_, let x), _), .Y(.C, let x), .Z(let x, _):
// CHECK: [[Y]]({{%.*}} : $(Foo, Int)):
// CHECK: [[Y_F:%.*]] = tuple_extract
// CHECK: [[Y_X:%.*]] = tuple_extract
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]({{%.*}} : $(Int, Foo)):
// CHECK: [[Z_X:%.*]] = tuple_extract
// CHECK: [[Z_F:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: [[FUNC_A:%.*]] = function_ref @$S10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
func aaa(x x: inout Int) {}
// CHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns5yyF : $@convention(thin) () -> () {
func test_multiple_patterns5() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(var x, _), _), .Y(.B(_, var x), _), .Y(.C, var x), .Z(var x, _):
// CHECK: [[Y]]({{%.*}} : $(Foo, Int)):
// CHECK: [[Y_F:%.*]] = tuple_extract
// CHECK: [[Y_X:%.*]] = tuple_extract
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]({{%.*}} : $(Int, Foo)):
// CHECK: [[Z_X:%.*]] = tuple_extract
// CHECK: [[Z_F:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: store [[BODY_X]] to [trivial] [[BOX_X:%.*]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOX_X]]
// CHECK: [[FUNC_AAA:%.*]] = function_ref @$S10switch_var3aaa1xySiz_tF
// CHECK: apply [[FUNC_AAA]]([[WRITE]])
aaa(x: &x)
}
}
// rdar://problem/29252758 -- local decls must not be reemitted.
func test_against_reemission(x: Bar) {
switch x {
case .Y(let a, _), .Z(_, let a):
let b = a
}
}
class C {}
class D: C {}
func f(_: D) -> Bool { return true }
// CHECK-LABEL: sil hidden @{{.*}}test_multiple_patterns_value_semantics
func test_multiple_patterns_value_semantics(_ y: C) {
switch y {
// CHECK: checked_cast_br {{%.*}} : $C to $D, [[AS_D:bb[0-9]+]], [[NOT_AS_D:bb[0-9]+]]
// CHECK: [[AS_D]]({{.*}}):
// CHECK: cond_br {{%.*}}, [[F_TRUE:bb[0-9]+]], [[F_FALSE:bb[0-9]+]]
// CHECK: [[F_TRUE]]:
// CHECK: [[BINDING:%.*]] = copy_value [[ORIG:%.*]] :
// CHECK: destroy_value [[ORIG]]
// CHECK: br {{bb[0-9]+}}([[BINDING]]
case let x as D where f(x), let x as D: break
default: break
}
}
|
apache-2.0
|
a3702324311c24ec3909110e5a8acfbb
| 36.541005 | 161 | 0.510659 | 2.859547 | false | false | false | false |
fanyinan/WZMessageKit
|
WZMessageKitDemo/WZMessageKitDemo/WZMessageKitDemo/WZMessageMenuView.swift
|
1
|
3176
|
//
// WZMessageMenuView.swift
// WZMessageProject
//
// Created by 范祎楠 on 16/3/7.
// Copyright © 2016年 范祎楠. All rights reserved.
//
import UIKit
struct MessageMenuItem {
var imageName = ""
var title = ""
var subtitle = ""
var enable = true
}
protocol WZMessageMenuViewDelegate: NSObjectProtocol {
func menuView(_ menuView: WZMessageMenuView, didSelectItemAtIndex menuItemIndex: Int)
}
class WZMessageMenuView: UIView {
fileprivate weak var delegate: WZMessageMenuViewDelegate?
private var collectionView: UICollectionView!
var menuDataList: [MessageMenuItem] = []
var canAudio = false
var canVideo = false
var numberOfCol: CGFloat = 4
var numberOfRow = 1
var hMargin: CGFloat = 30
var vMargin: CGFloat = 20
let itemWidth: CGFloat = 60
init(delegate: WZMessageMenuViewDelegate, frame: CGRect) {
self.delegate = delegate
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func reload() {
collectionView.reloadData()
}
func setupUI() {
backgroundColor = .white
let collectionViewFlowLayout = UICollectionViewFlowLayout()
collectionViewFlowLayout.itemSize = CGSize(width: itemWidth, height: frame.height - vMargin * 2)
collectionViewFlowLayout.minimumInteritemSpacing = (frame.width - hMargin * 2 - itemWidth * CGFloat(numberOfCol)) / (CGFloat(numberOfCol) - 1)
collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: collectionViewFlowLayout)
addSubview(collectionView)
collectionView.snp.makeConstraints { (make) in
make.edges.equalToSuperview().inset(UIEdgeInsets(top: vMargin, left: hMargin, bottom: vMargin, right: hMargin))
}
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = .white
collectionView.register(UINib(nibName: "MessageMenuCell", bundle: nil ), forCellWithReuseIdentifier: "MessageMenuCell")
}
func menuItemClick(_ sender: UIControl) {
delegate?.menuView(self, didSelectItemAtIndex: sender.tag)
}
}
extension WZMessageMenuView: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return menuDataList.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MessageMenuCell", for: indexPath) as! MessageMenuCell
cell.setData(messageMenuItem: menuDataList[indexPath.row])
cell.iconImageView.alpha = 1
if indexPath.row == 1 {
cell.iconImageView.alpha = canVideo ? 1 : 0.2
}
if indexPath.row == 2 {
cell.iconImageView.alpha = canAudio ? 1 : 0.2
}
return cell
}
}
extension WZMessageMenuView: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.menuView(self, didSelectItemAtIndex: indexPath.row)
}
}
|
bsd-2-clause
|
e860730a4ea35164e26e1abcf49a636c
| 27.223214 | 146 | 0.716862 | 4.724963 | false | false | false | false |
FutureKit/FutureKit
|
FutureKit/FoundationExtensions/NSData-Ext.swift
|
1
|
5150
|
//
// NSData-Ext.swift
// FutureKit
//
// Created by Michael Gray on 4/21/15.
// 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
/**
FutureKit extension for NSData. Including class functions replacements for the thread-blocking NSData(contentsOfFile::) and NSData(contentsOfURL::)
*/
extension Data {
/**
FutureKit extension for NSData.
uses executor to read from path. The default configuration of Executor.Async is QOS_CLASS_DEFAULT.
alternative use `class func data(executor : Executor, contentsOfFile path: String, options readOptionsMask: NSDataReadingOptions)`
- returns: an Future<NSData>
*/
static func data(_ executor : Executor, contentsOfFile path: String, options readOptionsMask: NSData.ReadingOptions) -> Future<Data> {
return executor.execute { () -> Data in
return try Data(contentsOf: URL(fileURLWithPath: path), options: readOptionsMask)
}
}
/**
FutureKit extension for NSData
uses `Executor.Async` to read from path. The default configuration of Executor.Async is QOS_CLASS_DEFAULT.
alternative use `class func data(executor : Executor, contentsOfFile path: String, options readOptionsMask: NSDataReadingOptions)`
- returns: an Future<NSData>
*/
static func data(contentsOfFile path: String, options readOptionsMask: NSData.ReadingOptions) -> Future<Data> {
return self.data(.async, contentsOfFile: path, options: readOptionsMask)
}
/**
FutureKit extension for NSData
uses executor to read from path. The default configuration of Executor.Async is QOS_CLASS_DEFAULT.
alternative use `class func data(executor : Executor, contentsOfFile path: String, options readOptionsMask: NSDataReadingOptions)`
example:
let d = NSData.data(.Async,url,DataReadingUncached).onSuccess(.Main) { (data) -> Void in
// use my data!
}
- returns: an Future<NSData>
*/
static func data(_ executor : Executor, contentsOfURL url: URL, options readOptionsMask: NSData.ReadingOptions) -> Future<Data> {
return executor.execute { () -> Data in
let data = try Data(contentsOf: url, options: readOptionsMask)
return data
}
}
/**
FutureKit extension for NSData
uses `Executor.Async` to read from path. The default configuration of Executor.Async is QOS_CLASS_DEFAULT.
alternative use `class func data(executor : Executor, contentsOfFile path: String, options readOptionsMask: NSDataReadingOptions)`
- returns: an Future<NSData>
*/
static func data(contentsOfURL url: URL, options readOptionsMask: NSData.ReadingOptions) -> Future<Data> {
return self.data(.async, contentsOfURL: url, options: readOptionsMask)
}
/**
FutureKit extension for NSData
uses executor to read from contentsOfURL. The default configuration of Executor.Async is QOS_CLASS_DEFAULT.
alternative use `class func data(executor : Executor, contentsOfFile path: String, options readOptionsMask: NSDataReadingOptions)`
- returns: an Future<NSData>
*/
static func data(_ executor : Executor, contentsOfURL url: URL) -> Future<Data> {
let promise = Promise<Data>()
executor.execute { () -> Void in
let data = try? Data(contentsOf: url)
if let d = data {
promise.completeWithSuccess(d)
}
else {
promise.completeWithFail("nil returned from NSData(contentsOfURL:\(url))")
}
}
return promise.future
}
/**
FutureKit extension for NSData
uses `Executor.Async` to read from path. The default configuration of Executor.Async is QOS_CLASS_DEFAULT.
- returns: an Future<NSData>. Fails of NSData(contentsOfUrl:url) returns a nil.
*/
static func data(contentsOfURL url: URL) -> Future<Data> {
return self.data(.async, contentsOfURL: url)
}
}
|
mit
|
e146e43ff99cb75b14d96e55a5875e81
| 37.148148 | 148 | 0.678835 | 4.844779 | false | false | false | false |
hooman/swift
|
test/IRGen/enum_derived.swift
|
13
|
2572
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -module-name def_enum -o %t %S/Inputs/def_enum.swift
// RUN: %target-swift-frontend -I %t -O -primary-file %s -emit-ir | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-NORMAL %s
// RUN: %target-swift-frontend -I %t -O -primary-file %s -enable-testing -emit-ir | %FileCheck -check-prefix=CHECK -check-prefix=CHECK-TESTABLE %s
import def_enum
// Check if hashValue, hash(into:) and == for an enum (without payload) are
// generated and check that functions are compiled in an optimal way.
enum E {
case E0
case E1
case E2
case E3
}
// Check if the == comparison can be compiled to a simple icmp instruction.
// CHECK-NORMAL-LABEL:define hidden swiftcc i1 @"$s12enum_derived1EO02__b1_A7_equalsySbAC_ACtFZ"(i8 %0, i8 %1)
// CHECK-TESTABLE-LABEL:define{{( dllexport)?}}{{( protected)?}} swiftcc i1 @"$s12enum_derived1EO02__b1_A7_equalsySbAC_ACtFZ"(i8 %0, i8 %1)
// CHECK: %2 = icmp eq i8 %0, %1
// CHECK: ret i1 %2
// Check if the hash(into:) method can be compiled to a simple zext instruction
// followed by a call to Hasher._combine(_:).
// CHECK-NORMAL-LABEL:define hidden swiftcc void @"$s12enum_derived1EO4hash4intoys6HasherVz_tF"
// CHECK-TESTABLE-LABEL:define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s12enum_derived1EO4hash4intoys6HasherVz_tF"
// CHECK: [[V:%.*]] = zext i8 %1 to i{{.*}}
// CHECK: tail call swiftcc void @"$ss6HasherV8_combineyySuF"(i{{.*}} [[V]], %Ts6HasherV*
// CHECK: ret void
// Check for the presence of the hashValue getter, calling Hasher.init() and
// Hasher.finalize().
// CHECK-NORMAL-LABEL:define hidden swiftcc i{{.*}} @"$s12enum_derived1EO9hashValueSivg"(i8 %0)
// CHECK-TESTABLE-LABEL:define{{( dllexport)?}}{{( protected)?}} swiftcc i{{.*}} @"$s12enum_derived1EO9hashValueSivg"(i8 %0)
// CHECK: call swiftcc void @"$ss6HasherV5_seedABSi_tcfC"(%Ts6HasherV* {{.*}})
// CHECK: call swiftcc i{{[0-9]+}} @"$ss6HasherV9_finalizeSiyF"(%Ts6HasherV* {{.*}})
// CHECK: ret i{{[0-9]+}} %{{[0-9]+}}
// Derived conformances from extensions
// The actual enums are in Inputs/def_enum.swift
extension def_enum.TrafficLight : Error {}
extension def_enum.Term : Error {}
// CHECK-NORMAL-LABEL: define hidden {{.*}}i64 @"$s12enum_derived7PhantomO8rawValues5Int64Vvg"(i8 %0, %swift.type* nocapture readnone %T) local_unnamed_addr
// CHECK-TESTABLE-LABEL: define{{( dllexport)?}}{{( protected)?}} {{.*}}i64 @"$s12enum_derived7PhantomO8rawValues5Int64Vvg"(i8 %0, %swift.type* nocapture readnone %T)
enum Phantom<T> : Int64 {
case Up
case Down
}
|
apache-2.0
|
69801da9022ce94dcea96e99b4098699
| 44.928571 | 166 | 0.69479 | 3.151961 | false | true | false | false |
lenssss/whereAmI
|
Whereami/Controller/Personal/MessageTextView.swift
|
1
|
3768
|
//
// MessageTextView.swift
// ChatView
//
// Created by 吴启飞 on 16/4/27.
// Copyright © 2016年 Amazing W. All rights reserved.
//
import UIKit
import ReactiveCocoa
class MessageTextView: UITextView {
var maxCharacerPerLine:Int {
return 33
}
private var _placeHolder:String = "Write Something ..."
var placeHolder:String = "Write Something ..." {
willSet(newValue) {
if newValue == placeHolder {
return
}
var dealedValue = ""
if newValue.characters.count > maxCharacerPerLine {
let length = maxCharacerPerLine - 8
dealedValue = newValue.substring(0, length: length)
dealedValue.appendContentsOf("...")
}else {
dealedValue = newValue
}
_placeHolder = dealedValue
}
didSet {
if placeHolder != _placeHolder {
placeHolder = _placeHolder
}
self.setNeedsDisplay()
}
}
private var _placeHolderTextColor:UIColor = UIColor.lightGrayColor()
var placeHolderTextColor:UIColor = UIColor.lightGrayColor() {
willSet (newValue) {
if newValue.isEqual(placeHolderTextColor) {
return
}
_placeHolderTextColor = newValue
}
didSet {
if placeHolderTextColor != _placeHolderTextColor {
placeHolderTextColor = _placeHolderTextColor
}
}
}
func numberOfLinesOfText()->(Int) {
let lines = text.length / maxCharacerPerLine + 1
return lines
}
func setup() {
LNotificationCenter().rac_addObserverForName(UITextViewTextDidChangeNotification, object: nil).subscribeNext { (anyObj) in
self.setNeedsDisplay()
}
self.placeHolderTextColor = UIColor.lightGrayColor()
self.autoresizingMask = .FlexibleWidth
self.scrollIndicatorInsets = UIEdgeInsetsMake(10.0, 0.0, 10.0, 8.0)
self.contentInset = UIEdgeInsetsZero
self.scrollEnabled = true
self.scrollsToTop = false
self.userInteractionEnabled = true
self.font = UIFont.systemFontOfSize(16.0)
self.textColor = UIColor.lightGrayColor()
self.backgroundColor = UIColor.whiteColor()
self.keyboardAppearance = .Default;
self.keyboardType = .Default;
self.returnKeyType = .Default;
self.textAlignment = .Left;
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
super.drawRect(rect)
if self.text.length == 0 && self.placeHolder.length > 0 {
let placeHolderRect = CGRect(x: 10,y: 7.0,width: rect.width,height: rect.height)
self.placeHolderTextColor.set()
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .ByTruncatingTail
paragraphStyle.alignment = self.textAlignment
(self.placeHolder as NSString).drawInRect(placeHolderRect, withAttributes: [NSFontAttributeName:self.font!,NSForegroundColorAttributeName:self.placeHolderTextColor,NSParagraphStyleAttributeName:paragraphStyle])
}
}
}
|
mit
|
a91cb0e5f767834c58fc1fca652ed314
| 31.686957 | 222 | 0.600692 | 5.347084 | false | false | false | false |
FelixSFD/FDRatingView
|
Shared/FDSquareView.swift
|
1
|
3316
|
//
// FDSquareView.swift
// FDRatingView
//
// Created by Felix Deil on 15.05.16.
// Copyright © 2016 Felix Deil. All rights reserved.
//
//import UIKit
import QuartzCore
import CoreGraphics
/**
This `UIView` displays a square, that can be fully or partially filled.
- author: Felix Deil
*/
internal class FDSquareView: FDRatingElementView {
// - MARK: Private properties
/**
The layer that draws a fully filled square
*/
private var fullSquare: CAShapeLayer!
/**
The layer that draws the border of a star
*/
private var borderSquare: CAShapeLayer!
override internal var tintColor: FDColor! {
get {
return FDColor.black
}
set (color) {
fullSquare.fillColor = color.cgColor
borderSquare.strokeColor = color.cgColor
}
}
// - MARK: Initialize the View
/**
Initializes the `FDSquareView`
- parameter frame: The frame for the view
- parameter fillValue: `Float` bewteen 0 and 1
- parameter color: The color of the square. Not the background of the view. Acts like `tintColor`
- paramter lineWidth: The with of the border-line (default is 1, but for really small squares, lower values are recommended)
- author: Felix Deil
*/
internal init(frame: CGRect, fillValue fill: Float, color fillColor: FDColor, lineWidth: CGFloat) {
super.init(frame: frame)
//layer for complete filled star
fullSquare = CAShapeLayer()
fullSquare.path = FDBezierPath(rect: CGRect(x: 0, y: 0, width: frame.size.height, height: frame.size.height)).cgPath
fullSquare.fillColor = fillColor.cgColor
self.layer.addSublayer(fullSquare)
//layer for border
borderSquare = CAShapeLayer()
borderSquare.path = fullSquare.path
borderSquare.fillColor = FDColor.clear.cgColor
borderSquare.lineWidth = lineWidth
borderSquare.strokeColor = fillColor.cgColor
self.layer.addSublayer(borderSquare)
//create fill-mask
let fillWidth = frame.size.width * CGFloat(fill)
let fillPath = FDBezierPath(roundedRect: CGRect(x: 0, y: 0, width: fillWidth, height: frame.size.height), cornerRadius: 0)
fillMask = CAShapeLayer()
fillMask.path = fillPath.cgPath
fullSquare.mask = fillMask
}
/**
Initializes the `FDSquareView`
- parameter frame: The frame for the view
- parameter fillValue: `Float` bewteen 0 and 1
- parameter color: The color of the square. Not the background of the view. Acts like `tintColor`
- author: Felix Deil
*/
internal convenience init(frame: CGRect, fillValue fill: Float, color fillColor: FDColor) {
self.init(frame:frame, fillValue: fill, color: fillColor, lineWidth: 1)
}
/**
Initializes the view with a frame
*/
override private init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = FDColor.clear
tintColor = FDView().tintColor
}
required internal init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
apache-2.0
|
4b7360b5443b3b66f0301b58c6b4e6c5
| 28.336283 | 130 | 0.626546 | 4.473684 | false | false | false | false |
parkera/swift-corelibs-foundation
|
Foundation/Data.swift
|
1
|
127791
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#if DEPLOYMENT_RUNTIME_SWIFT
#if !canImport(Darwin)
@inlinable // This is @inlinable as trivially computable.
internal func malloc_good_size(_ size: Int) -> Int {
return size
}
#endif
import CoreFoundation
internal func __NSDataInvokeDeallocatorUnmap(_ mem: UnsafeMutableRawPointer, _ length: Int) {
#if os(Windows)
UnmapViewOfFile(mem)
#else
munmap(mem, length)
#endif
}
internal func __NSDataInvokeDeallocatorFree(_ mem: UnsafeMutableRawPointer, _ length: Int) {
free(mem)
}
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
return data._isCompact()
}
#else
@_exported import Foundation // Clang module
import _SwiftFoundationOverlayShims
import _SwiftCoreFoundationOverlayShims
internal func __NSDataIsCompact(_ data: NSData) -> Bool {
if #available(OSX 10.10, iOS 8.0, tvOS 9.0, watchOS 2.0, *) {
return data._isCompact()
} else {
var compact = true
let len = data.length
data.enumerateBytes { (_, byteRange, stop) in
if byteRange.length != len {
compact = false
}
stop.pointee = true
}
return compact
}
}
#endif
// Underlying storage representation for medium and large data.
// Inlinability strategy: methods from here should not inline into InlineSlice or LargeSlice unless trivial.
// NOTE: older overlays called this class _DataStorage. The two must
// coexist without a conflicting ObjC class name, so it was renamed.
// The old name must not be used in the new runtime.
@usableFromInline
internal final class __DataStorage {
@usableFromInline static let maxSize = Int.max >> 1
@usableFromInline static let vmOpsThreshold = NSPageSize() * 4
@inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer.
static func allocate(_ size: Int, _ clear: Bool) -> UnsafeMutableRawPointer? {
if clear {
return calloc(1, size)
} else {
return malloc(size)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
static func move(_ dest_: UnsafeMutableRawPointer, _ source_: UnsafeRawPointer?, _ num_: Int) {
var dest = dest_
var source = source_
var num = num_
if __DataStorage.vmOpsThreshold <= num && ((unsafeBitCast(source, to: Int.self) | Int(bitPattern: dest)) & (NSPageSize() - 1)) == 0 {
let pages = NSRoundDownToMultipleOfPageSize(num)
NSCopyMemoryPages(source!, dest, pages)
source = source!.advanced(by: pages)
dest = dest.advanced(by: pages)
num -= pages
}
if num > 0 {
memmove(dest, source!, num)
}
}
@inlinable // This is @inlinable as trivially forwarding, and does not escape the _DataStorage boundary layer.
static func shouldAllocateCleared(_ size: Int) -> Bool {
return (size > (128 * 1024))
}
@usableFromInline var _bytes: UnsafeMutableRawPointer?
@usableFromInline var _length: Int
@usableFromInline var _capacity: Int
@usableFromInline var _needToZero: Bool
@usableFromInline var _deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?
@usableFromInline var _offset: Int
@inlinable // This is @inlinable as trivially computable.
var bytes: UnsafeRawPointer? {
return UnsafeRawPointer(_bytes)?.advanced(by: -_offset)
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding.
@discardableResult
func withUnsafeBytes<Result>(in range: Range<Int>, apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
return try apply(UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)))
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially forwarding.
@discardableResult
func withUnsafeMutableBytes<Result>(in range: Range<Int>, apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
return try apply(UnsafeMutableRawBufferPointer(start: _bytes!.advanced(by:range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length)))
}
@inlinable // This is @inlinable as trivially computable.
var mutableBytes: UnsafeMutableRawPointer? {
return _bytes?.advanced(by: -_offset)
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return _capacity
}
@inlinable // This is @inlinable as trivially computable.
var length: Int {
get {
return _length
}
set {
setLength(newValue)
}
}
@inlinable // This is inlinable as trivially computable.
var isExternallyOwned: Bool {
// all __DataStorages will have some sort of capacity, because empty cases hit the .empty enum _Representation
// anything with 0 capacity means that we have not allocated this pointer and consequently mutation is not ours to make.
return _capacity == 0
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func ensureUniqueBufferReference(growingTo newLength: Int = 0, clear: Bool = false) {
guard isExternallyOwned || newLength > _capacity else { return }
if newLength == 0 {
if isExternallyOwned {
let newCapacity = malloc_good_size(_length)
let newBytes = __DataStorage.allocate(newCapacity, false)
__DataStorage.move(newBytes!, _bytes!, _length)
_freeBytes()
_bytes = newBytes
_capacity = newCapacity
_needToZero = false
}
} else if isExternallyOwned {
let newCapacity = malloc_good_size(newLength)
let newBytes = __DataStorage.allocate(newCapacity, clear)
if let bytes = _bytes {
__DataStorage.move(newBytes!, bytes, _length)
}
_freeBytes()
_bytes = newBytes
_capacity = newCapacity
_length = newLength
_needToZero = true
} else {
let cap = _capacity
var additionalCapacity = (newLength >> (__DataStorage.vmOpsThreshold <= newLength ? 2 : 1))
if Int.max - additionalCapacity < newLength {
additionalCapacity = 0
}
var newCapacity = malloc_good_size(Swift.max(cap, newLength + additionalCapacity))
let origLength = _length
var allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity)
var newBytes: UnsafeMutableRawPointer? = nil
if _bytes == nil {
newBytes = __DataStorage.allocate(newCapacity, allocateCleared)
if newBytes == nil {
/* Try again with minimum length */
allocateCleared = clear && __DataStorage.shouldAllocateCleared(newLength)
newBytes = __DataStorage.allocate(newLength, allocateCleared)
}
} else {
let tryCalloc = (origLength == 0 || (newLength / origLength) >= 4)
if allocateCleared && tryCalloc {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
/* Where calloc/memmove/free fails, realloc might succeed */
if newBytes == nil {
allocateCleared = false
if _deallocator != nil {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
} else {
newBytes = realloc(_bytes!, newCapacity)
}
}
/* Try again with minimum length */
if newBytes == nil {
newCapacity = malloc_good_size(newLength)
allocateCleared = clear && __DataStorage.shouldAllocateCleared(newCapacity)
if allocateCleared && tryCalloc {
newBytes = __DataStorage.allocate(newCapacity, true)
if let newBytes = newBytes {
__DataStorage.move(newBytes, _bytes!, origLength)
_freeBytes()
}
}
if newBytes == nil {
allocateCleared = false
newBytes = realloc(_bytes!, newCapacity)
}
}
}
if newBytes == nil {
/* Could not allocate bytes */
// At this point if the allocation cannot occur the process is likely out of memory
// and Bad-Things™ are going to happen anyhow
fatalError("unable to allocate memory for length (\(newLength))")
}
if origLength < newLength && clear && !allocateCleared {
memset(newBytes!.advanced(by: origLength), 0, newLength - origLength)
}
/* _length set by caller */
_bytes = newBytes
_capacity = newCapacity
/* Realloc/memset doesn't zero out the entire capacity, so we must be safe and clear next time we grow the length */
_needToZero = !allocateCleared
}
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func _freeBytes() {
if let bytes = _bytes {
if let dealloc = _deallocator {
dealloc(bytes, length)
} else {
free(bytes)
}
}
_deallocator = nil
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func enumerateBytes(in range: Range<Int>, _ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Data.Index, _ stop: inout Bool) -> Void) {
var stopv: Bool = false
block(UnsafeBufferPointer<UInt8>(start: _bytes?.advanced(by: range.lowerBound - _offset).assumingMemoryBound(to: UInt8.self), count: Swift.min(range.upperBound - range.lowerBound, _length)), 0, &stopv)
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func setLength(_ length: Int) {
let origLength = _length
let newLength = length
if _capacity < newLength || _bytes == nil {
ensureUniqueBufferReference(growingTo: newLength, clear: true)
} else if origLength < newLength && _needToZero {
memset(_bytes! + origLength, 0, newLength - origLength)
} else if newLength < origLength {
_needToZero = true
}
_length = newLength
}
@inlinable // This is @inlinable as it does not escape the _DataStorage boundary layer.
func append(_ bytes: UnsafeRawPointer, length: Int) {
precondition(length >= 0, "Length of appending bytes must not be negative")
let origLength = _length
let newLength = origLength + length
if _capacity < newLength || _bytes == nil {
ensureUniqueBufferReference(growingTo: newLength, clear: false)
}
_length = newLength
__DataStorage.move(_bytes!.advanced(by: origLength), bytes, length)
}
@inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed.
func get(_ index: Int) -> UInt8 {
return _bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func set(_ index: Int, to value: UInt8) {
ensureUniqueBufferReference()
_bytes!.advanced(by: index - _offset).assumingMemoryBound(to: UInt8.self).pointee = value
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is trivially computed.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
let offsetPointer = UnsafeRawBufferPointer(start: _bytes?.advanced(by: range.lowerBound - _offset), count: Swift.min(range.upperBound - range.lowerBound, _length))
UnsafeMutableRawBufferPointer(start: pointer, count: range.upperBound - range.lowerBound).copyMemory(from: offsetPointer)
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func replaceBytes(in range_: NSRange, with replacementBytes: UnsafeRawPointer?, length replacementLength: Int) {
let range = NSRange(location: range_.location - _offset, length: range_.length)
let currentLength = _length
let resultingLength = currentLength - range.length + replacementLength
let shift = resultingLength - currentLength
let mutableBytes: UnsafeMutableRawPointer
if resultingLength > currentLength {
ensureUniqueBufferReference(growingTo: resultingLength)
_length = resultingLength
} else {
ensureUniqueBufferReference()
}
mutableBytes = _bytes!
/* shift the trailing bytes */
let start = range.location
let length = range.length
if shift != 0 {
memmove(mutableBytes + start + replacementLength, mutableBytes + start + length, currentLength - start - length)
}
if replacementLength != 0 {
if let replacementBytes = replacementBytes {
memmove(mutableBytes + start, replacementBytes, replacementLength)
} else {
memset(mutableBytes + start, 0, replacementLength)
}
}
if resultingLength < currentLength {
setLength(resultingLength)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func resetBytes(in range_: Range<Int>) {
let range = NSRange(location: range_.lowerBound - _offset, length: range_.upperBound - range_.lowerBound)
if range.length == 0 { return }
if _length < range.location + range.length {
let newLength = range.location + range.length
if _capacity <= newLength {
ensureUniqueBufferReference(growingTo: newLength, clear: false)
}
_length = newLength
} else {
ensureUniqueBufferReference()
}
memset(_bytes!.advanced(by: range.location), 0, range.length)
}
@usableFromInline // This is not @inlinable as a non-trivial, non-convenience initializer.
init(length: Int) {
precondition(length < __DataStorage.maxSize)
var capacity = (length < 1024 * 1024 * 1024) ? length + (length >> 2) : length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
let clear = __DataStorage.shouldAllocateCleared(length)
_bytes = __DataStorage.allocate(capacity, clear)!
_capacity = capacity
_needToZero = !clear
_length = 0
_offset = 0
setLength(length)
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(capacity capacity_: Int = 0) {
var capacity = capacity_
precondition(capacity < __DataStorage.maxSize)
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = 0
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
_offset = 0
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(bytes: UnsafeRawPointer?, length: Int) {
precondition(length < __DataStorage.maxSize)
_offset = 0
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
} else if __DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = __DataStorage.allocate(length, false)!
__DataStorage.move(_bytes!, bytes, length)
} else {
var capacity = length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
__DataStorage.move(_bytes!, bytes, length)
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(bytes: UnsafeMutableRawPointer?, length: Int, copy: Bool, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)?, offset: Int) {
precondition(length < __DataStorage.maxSize)
_offset = offset
if length == 0 {
_capacity = 0
_length = 0
_needToZero = false
_bytes = nil
if let dealloc = deallocator,
let bytes_ = bytes {
dealloc(bytes_, length)
}
} else if !copy {
_capacity = length
_length = length
_needToZero = false
_bytes = bytes
_deallocator = deallocator
} else if __DataStorage.vmOpsThreshold <= length {
_capacity = length
_length = length
_needToZero = true
_bytes = __DataStorage.allocate(length, false)!
__DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
} else {
var capacity = length
if __DataStorage.vmOpsThreshold <= capacity {
capacity = NSRoundUpToMultipleOfPageSize(capacity)
}
_length = length
_bytes = __DataStorage.allocate(capacity, false)!
_capacity = capacity
_needToZero = true
__DataStorage.move(_bytes!, bytes, length)
if let dealloc = deallocator {
dealloc(bytes!, length)
}
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(immutableReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: immutableReference.bytes)
_capacity = 0
_needToZero = false
_length = immutableReference.length
_deallocator = { _, _ in
_fixLifetime(immutableReference)
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(mutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = mutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = mutableReference.length
_deallocator = { _, _ in
_fixLifetime(mutableReference)
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(customReference: NSData, offset: Int) {
_offset = offset
_bytes = UnsafeMutableRawPointer(mutating: customReference.bytes)
_capacity = 0
_needToZero = false
_length = customReference.length
_deallocator = { _, _ in
_fixLifetime(customReference)
}
}
@usableFromInline // This is not @inlinable as a non-convenience initializer.
init(customMutableReference: NSMutableData, offset: Int) {
_offset = offset
_bytes = customMutableReference.mutableBytes
_capacity = 0
_needToZero = false
_length = customMutableReference.length
_deallocator = { _, _ in
_fixLifetime(customMutableReference)
}
}
deinit {
_freeBytes()
}
@inlinable // This is @inlinable despite escaping the __DataStorage boundary layer because it is trivially computed.
func mutableCopy(_ range: Range<Int>) -> __DataStorage {
return __DataStorage(bytes: _bytes?.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, copy: true, deallocator: nil, offset: range.lowerBound)
}
@inlinable // This is @inlinable despite escaping the _DataStorage boundary layer because it is generic and trivially computed.
func withInteriorPointerReference<T>(_ range: Range<Int>, _ work: (NSData) throws -> T) rethrows -> T {
if range.isEmpty {
return try work(NSData()) // zero length data can be optimized as a singleton
}
return try work(NSData(bytesNoCopy: _bytes!.advanced(by: range.lowerBound - _offset), length: range.upperBound - range.lowerBound, freeWhenDone: false))
}
@inline(never) // This is not @inlinable to avoid emission of the private `__NSSwiftData` class name into clients.
@usableFromInline
func bridgedReference(_ range: Range<Int>) -> NSData {
if range.isEmpty {
return NSData() // zero length data can be optimized as a singleton
}
return __NSSwiftData(backing: self, range: range)
}
}
// NOTE: older overlays called this _NSSwiftData. The two must
// coexist, so it was renamed. The old name must not be used in the new
// runtime.
internal class __NSSwiftData : NSData {
var _backing: __DataStorage!
var _range: Range<Data.Index>!
convenience init(backing: __DataStorage, range: Range<Data.Index>) {
self.init()
_backing = backing
_range = range
}
override var length: Int {
return _range.upperBound - _range.lowerBound
}
override var bytes: UnsafeRawPointer {
// NSData's byte pointer methods are not annotated for nullability correctly
// (but assume non-null by the wrapping macro guards). This placeholder value
// is to work-around this bug. Any indirection to the underlying bytes of an NSData
// with a length of zero would have been a programmer error anyhow so the actual
// return value here is not needed to be an allocated value. This is specifically
// needed to live like this to be source compatible with Swift3. Beyond that point
// this API may be subject to correction.
guard let bytes = _backing.bytes else {
return UnsafeRawPointer(bitPattern: 0xBAD0)!
}
return bytes.advanced(by: _range.lowerBound)
}
override func copy(with zone: NSZone? = nil) -> Any {
return self
}
override func mutableCopy(with zone: NSZone? = nil) -> Any {
return NSMutableData(bytes: bytes, length: length)
}
#if !DEPLOYMENT_RUNTIME_SWIFT
@objc override
func _isCompact() -> Bool {
return true
}
#endif
#if DEPLOYMENT_RUNTIME_SWIFT
override func _providesConcreteBacking() -> Bool {
return true
}
#else
@objc(_providesConcreteBacking)
func _providesConcreteBacking() -> Bool {
return true
}
#endif
}
@_fixed_layout
public struct Data : ReferenceConvertible, Equatable, Hashable, RandomAccessCollection, MutableCollection, RangeReplaceableCollection, MutableDataProtocol, ContiguousBytes {
public typealias ReferenceType = NSData
public typealias ReadingOptions = NSData.ReadingOptions
public typealias WritingOptions = NSData.WritingOptions
public typealias SearchOptions = NSData.SearchOptions
public typealias Base64EncodingOptions = NSData.Base64EncodingOptions
public typealias Base64DecodingOptions = NSData.Base64DecodingOptions
public typealias Index = Int
public typealias Indices = Range<Int>
// A small inline buffer of bytes suitable for stack-allocation of small data.
// Inlinability strategy: everything here should be inlined for direct operation on the stack wherever possible.
@usableFromInline
@_fixed_layout
internal struct InlineData {
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
@usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8) //len //enum
@usableFromInline var bytes: Buffer
#elseif arch(i386) || arch(arm)
@usableFromInline typealias Buffer = (UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8) //len //enum
@usableFromInline var bytes: Buffer
#endif
@usableFromInline var length: UInt8
@inlinable // This is @inlinable as trivially computable.
static func canStore(count: Int) -> Bool {
return count <= MemoryLayout<Buffer>.size
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ srcBuffer: UnsafeRawBufferPointer) {
self.init(count: srcBuffer.count)
if srcBuffer.count > 0 {
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
dstBuffer.baseAddress?.copyMemory(from: srcBuffer.baseAddress!, byteCount: srcBuffer.count)
}
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(count: Int = 0) {
assert(count <= MemoryLayout<Buffer>.size)
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0))
#elseif arch(i386) || arch(arm)
bytes = (UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0), UInt8(0))
#endif
length = UInt8(count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ slice: InlineSlice, count: Int) {
self.init(count: count)
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
slice.withUnsafeBytes { srcBuffer in
dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count))
}
}
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ slice: LargeSlice, count: Int) {
self.init(count: count)
Swift.withUnsafeMutableBytes(of: &bytes) { dstBuffer in
slice.withUnsafeBytes { srcBuffer in
dstBuffer.copyMemory(from: UnsafeRawBufferPointer(start: srcBuffer.baseAddress, count: count))
}
}
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return MemoryLayout<Buffer>.size
}
@inlinable // This is @inlinable as trivially computable.
var count: Int {
get {
return Int(length)
}
set(newValue) {
precondition(newValue <= MemoryLayout<Buffer>.size)
length = UInt8(newValue)
}
}
@inlinable // This is @inlinable as trivially computable.
var startIndex: Int {
return 0
}
@inlinable // This is @inlinable as trivially computable.
var endIndex: Int {
return count
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
let count = Int(length)
return try Swift.withUnsafeBytes(of: bytes) { (rawBuffer) throws -> Result in
return try apply(UnsafeRawBufferPointer(start: rawBuffer.baseAddress, count: count))
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
let count = Int(length)
return try Swift.withUnsafeMutableBytes(of: &bytes) { (rawBuffer) throws -> Result in
return try apply(UnsafeMutableRawBufferPointer(start: rawBuffer.baseAddress, count: count))
}
}
@inlinable // This is @inlinable as tribially computable.
mutating func append(byte: UInt8) {
let count = self.count
assert(count + 1 <= MemoryLayout<Buffer>.size)
Swift.withUnsafeMutableBytes(of: &bytes) { $0[count] = byte }
self.length += 1
}
@inlinable // This is @inlinable as trivially computable.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
guard buffer.count > 0 else { return }
assert(count + buffer.count <= MemoryLayout<Buffer>.size)
let cnt = count
_ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
rawBuffer.baseAddress?.advanced(by: cnt).copyMemory(from: buffer.baseAddress!, byteCount: buffer.count)
}
length += UInt8(buffer.count)
}
@inlinable // This is @inlinable as trivially computable.
subscript(index: Index) -> UInt8 {
get {
assert(index <= MemoryLayout<Buffer>.size)
precondition(index < length, "index \(index) is out of bounds of 0..<\(length)")
return Swift.withUnsafeBytes(of: bytes) { rawBuffer -> UInt8 in
return rawBuffer[index]
}
}
set(newValue) {
assert(index <= MemoryLayout<Buffer>.size)
precondition(index < length, "index \(index) is out of bounds of 0..<\(length)")
Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
rawBuffer[index] = newValue
}
}
}
@inlinable // This is @inlinable as trivially computable.
mutating func resetBytes(in range: Range<Index>) {
assert(range.lowerBound <= MemoryLayout<Buffer>.size)
assert(range.upperBound <= MemoryLayout<Buffer>.size)
precondition(range.lowerBound <= length, "index \(range.lowerBound) is out of bounds of 0..<\(length)")
if count < range.upperBound {
count = range.upperBound
}
let _ = Swift.withUnsafeMutableBytes(of: &bytes) { rawBuffer in
memset(rawBuffer.baseAddress!.advanced(by: range.lowerBound), 0, range.upperBound - range.lowerBound)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
mutating func replaceSubrange(_ subrange: Range<Index>, with replacementBytes: UnsafeRawPointer?, count replacementLength: Int) {
assert(subrange.lowerBound <= MemoryLayout<Buffer>.size)
assert(subrange.upperBound <= MemoryLayout<Buffer>.size)
assert(count - (subrange.upperBound - subrange.lowerBound) + replacementLength <= MemoryLayout<Buffer>.size)
precondition(subrange.lowerBound <= length, "index \(subrange.lowerBound) is out of bounds of 0..<\(length)")
precondition(subrange.upperBound <= length, "index \(subrange.lowerBound) is out of bounds of 0..<\(length)")
let currentLength = count
let resultingLength = currentLength - (subrange.upperBound - subrange.lowerBound) + replacementLength
let shift = resultingLength - currentLength
Swift.withUnsafeMutableBytes(of: &bytes) { mutableBytes in
/* shift the trailing bytes */
let start = subrange.lowerBound
let length = subrange.upperBound - subrange.lowerBound
if shift != 0 {
memmove(mutableBytes.baseAddress!.advanced(by: start + replacementLength), mutableBytes.baseAddress!.advanced(by: start + length), currentLength - start - length)
}
if replacementLength != 0 {
memmove(mutableBytes.baseAddress!.advanced(by: start), replacementBytes!, replacementLength)
}
}
count = resultingLength
}
@inlinable // This is @inlinable as trivially computable.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
Swift.withUnsafeBytes(of: bytes) {
let cnt = Swift.min($0.count, range.upperBound - range.lowerBound)
guard cnt > 0 else { return }
pointer.copyMemory(from: $0.baseAddress!.advanced(by: range.lowerBound), byteCount: cnt)
}
}
@inline(__always) // This should always be inlined into _Representation.hash(into:).
func hash(into hasher: inout Hasher) {
// **NOTE**: this uses `count` (an Int) and NOT `length` (a UInt8)
// Despite having the same value, they hash differently. InlineSlice and LargeSlice both use `count` (an Int); if you combine the same bytes but with `length` over `count`, you can get a different hash.
//
// This affects slices, which are InlineSlice and not InlineData:
//
// let d = Data([0xFF, 0xFF]) // InlineData
// let s = Data([0, 0xFF, 0xFF]).dropFirst() // InlineSlice
// assert(s == d)
// assert(s.hashValue == d.hashValue)
hasher.combine(count)
Swift.withUnsafeBytes(of: bytes) {
// We have access to the full byte buffer here, but not all of it is meaningfully used (bytes past self.length may be garbage).
let bytes = UnsafeRawBufferPointer(start: $0.baseAddress, count: self.count)
hasher.combine(bytes: bytes)
}
}
}
#if arch(x86_64) || arch(arm64) || arch(s390x) || arch(powerpc64) || arch(powerpc64le)
@usableFromInline internal typealias HalfInt = Int32
#elseif arch(i386) || arch(arm)
@usableFromInline internal typealias HalfInt = Int16
#endif
// A buffer of bytes too large to fit in an InlineData, but still small enough to fit a storage pointer + range in two words.
// Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here.
@usableFromInline
@_fixed_layout
internal struct InlineSlice {
// ***WARNING***
// These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last
@usableFromInline var slice: Range<HalfInt>
@usableFromInline var storage: __DataStorage
@inlinable // This is @inlinable as trivially computable.
static func canStore(count: Int) -> Bool {
return count < HalfInt.max
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ buffer: UnsafeRawBufferPointer) {
assert(buffer.count < HalfInt.max)
self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(capacity: Int) {
assert(capacity < HalfInt.max)
self.init(__DataStorage(capacity: capacity), count: 0)
}
@inlinable // This is @inlinable as a convenience initializer.
init(count: Int) {
assert(count < HalfInt.max)
self.init(__DataStorage(length: count), count: count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ inline: InlineData) {
assert(inline.count < HalfInt.max)
self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, count: inline.count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ inline: InlineData, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.init(inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }, range: range)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ large: LargeSlice) {
assert(large.range.lowerBound < HalfInt.max)
assert(large.range.upperBound < HalfInt.max)
self.init(large.storage, range: large.range)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ large: LargeSlice, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.init(large.storage, range: range)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, count: Int) {
assert(count < HalfInt.max)
self.storage = storage
slice = 0..<HalfInt(count)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, range: Range<Int>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
self.storage = storage
slice = HalfInt(range.lowerBound)..<HalfInt(range.upperBound)
}
@inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
mutating func ensureUniqueReference() {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.mutableCopy(self.range)
}
}
@inlinable // This is @inlinable as trivially computable.
var startIndex: Int {
return Int(slice.lowerBound)
}
@inlinable // This is @inlinable as trivially computable.
var endIndex: Int {
return Int(slice.upperBound)
}
@inlinable // This is @inlinable as trivially computable.
var capacity: Int {
return storage.capacity
}
@inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
mutating func reserveCapacity(_ minimumCapacity: Int) {
ensureUniqueReference()
// the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity
storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count))
}
@inlinable // This is @inlinable as trivially computable.
var count: Int {
get {
return Int(slice.upperBound - slice.lowerBound)
}
set(newValue) {
assert(newValue < HalfInt.max)
ensureUniqueReference()
storage.length = newValue
slice = slice.lowerBound..<(slice.lowerBound + HalfInt(newValue))
}
}
@inlinable // This is @inlinable as trivially computable.
var range: Range<Int> {
get {
return Int(slice.lowerBound)..<Int(slice.upperBound)
}
set(newValue) {
assert(newValue.lowerBound < HalfInt.max)
assert(newValue.upperBound < HalfInt.max)
slice = HalfInt(newValue.lowerBound)..<HalfInt(newValue.upperBound)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
return try storage.withUnsafeBytes(in: range, apply: apply)
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
ensureUniqueReference()
return try storage.withUnsafeMutableBytes(in: range, apply: apply)
}
@inlinable // This is @inlinable as reasonably small.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
assert(endIndex + buffer.count < HalfInt.max)
ensureUniqueReference()
storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count)
slice = slice.lowerBound..<HalfInt(Int(slice.upperBound) + buffer.count)
}
@inlinable // This is @inlinable as reasonably small.
subscript(index: Index) -> UInt8 {
get {
assert(index < HalfInt.max)
precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
return storage.get(index)
}
set(newValue) {
assert(index < HalfInt.max)
precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
ensureUniqueReference()
storage.set(index, to: newValue)
}
}
@inlinable // This is @inlinable as trivially forwarding.
func bridgedReference() -> NSData {
return storage.bridgedReference(self.range)
}
@inlinable // This is @inlinable as reasonably small.
mutating func resetBytes(in range: Range<Index>) {
assert(range.lowerBound < HalfInt.max)
assert(range.upperBound < HalfInt.max)
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
ensureUniqueReference()
storage.resetBytes(in: range)
if slice.upperBound < range.upperBound {
slice = slice.lowerBound..<HalfInt(range.upperBound)
}
}
@inlinable // This is @inlinable as reasonably small.
mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound)
ensureUniqueReference()
let upper = range.upperBound
storage.replaceBytes(in: nsRange, with: bytes, length: cnt)
let resultingUpper = upper - nsRange.length + cnt
slice = slice.lowerBound..<HalfInt(resultingUpper)
}
@inlinable // This is @inlinable as reasonably small.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
storage.copyBytes(to: pointer, from: range)
}
@inline(__always) // This should always be inlined into _Representation.hash(into:).
func hash(into hasher: inout Hasher) {
hasher.combine(count)
// At most, hash the first 80 bytes of this data.
let range = startIndex ..< Swift.min(startIndex + 80, endIndex)
storage.withUnsafeBytes(in: range) {
hasher.combine(bytes: $0)
}
}
}
// A reference wrapper around a Range<Int> for when the range of a data buffer is too large to whole in a single word.
// Inlinability strategy: everything should be inlinable as trivial.
@usableFromInline
@_fixed_layout
internal final class RangeReference {
@usableFromInline var range: Range<Int>
@inlinable @inline(__always) // This is @inlinable as trivially forwarding.
var lowerBound: Int {
return range.lowerBound
}
@inlinable @inline(__always) // This is @inlinable as trivially forwarding.
var upperBound: Int {
return range.upperBound
}
@inlinable @inline(__always) // This is @inlinable as trivially computable.
var count: Int {
return range.upperBound - range.lowerBound
}
@inlinable @inline(__always) // This is @inlinable as a trivial initializer.
init(_ range: Range<Int>) {
self.range = range
}
}
// A buffer of bytes whose range is too large to fit in a signle word. Used alongside a RangeReference to make it fit into _Representation's two-word size.
// Inlinability strategy: everything here should be easily inlinable as large _DataStorage methods should not inline into here.
@usableFromInline
@_fixed_layout
internal struct LargeSlice {
// ***WARNING***
// These ivars are specifically laid out so that they cause the enum _Representation to be 16 bytes on 64 bit platforms. This means we _MUST_ have the class type thing last
@usableFromInline var slice: RangeReference
@usableFromInline var storage: __DataStorage
@inlinable // This is @inlinable as a convenience initializer.
init(_ buffer: UnsafeRawBufferPointer) {
self.init(__DataStorage(bytes: buffer.baseAddress, length: buffer.count), count: buffer.count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(capacity: Int) {
self.init(__DataStorage(capacity: capacity), count: 0)
}
@inlinable // This is @inlinable as a convenience initializer.
init(count: Int) {
self.init(__DataStorage(length: count), count: count)
}
@inlinable // This is @inlinable as a convenience initializer.
init(_ inline: InlineData) {
let storage = inline.withUnsafeBytes { return __DataStorage(bytes: $0.baseAddress, length: $0.count) }
self.init(storage, count: inline.count)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ slice: InlineSlice) {
self.storage = slice.storage
self.slice = RangeReference(slice.range)
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, count: Int) {
self.storage = storage
self.slice = RangeReference(0..<count)
}
@inlinable // This is @inlinable as trivially computable (and inlining may help avoid retain-release traffic).
mutating func ensureUniqueReference() {
if !isKnownUniquelyReferenced(&storage) {
storage = storage.mutableCopy(range)
}
if !isKnownUniquelyReferenced(&slice) {
slice = RangeReference(range)
}
}
@inlinable // This is @inlinable as trivially forwarding.
var startIndex: Int {
return slice.range.lowerBound
}
@inlinable // This is @inlinable as trivially forwarding.
var endIndex: Int {
return slice.range.upperBound
}
@inlinable // This is @inlinable as trivially forwarding.
var capacity: Int {
return storage.capacity
}
@inlinable // This is @inlinable as trivially computable.
mutating func reserveCapacity(_ minimumCapacity: Int) {
ensureUniqueReference()
// the current capacity can be zero (representing externally owned buffer), and count can be greater than the capacity
storage.ensureUniqueBufferReference(growingTo: Swift.max(minimumCapacity, count))
}
@inlinable // This is @inlinable as trivially computable.
var count: Int {
get {
return slice.count
}
set(newValue) {
ensureUniqueReference()
storage.length = newValue
slice.range = slice.range.lowerBound..<(slice.range.lowerBound + newValue)
}
}
@inlinable // This is @inlinable as it is trivially forwarding.
var range: Range<Int> {
return slice.range
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
return try storage.withUnsafeBytes(in: range, apply: apply)
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
ensureUniqueReference()
return try storage.withUnsafeMutableBytes(in: range, apply: apply)
}
@inlinable // This is @inlinable as reasonably small.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
ensureUniqueReference()
storage.replaceBytes(in: NSRange(location: range.upperBound, length: storage.length - (range.upperBound - storage._offset)), with: buffer.baseAddress, length: buffer.count)
slice.range = slice.range.lowerBound..<slice.range.upperBound + buffer.count
}
@inlinable // This is @inlinable as trivially computable.
subscript(index: Index) -> UInt8 {
get {
precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
return storage.get(index)
}
set(newValue) {
precondition(startIndex <= index, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(index < endIndex, "index \(index) is out of bounds of \(startIndex)..<\(endIndex)")
ensureUniqueReference()
storage.set(index, to: newValue)
}
}
@inlinable // This is @inlinable as trivially forwarding.
func bridgedReference() -> NSData {
return storage.bridgedReference(self.range)
}
@inlinable // This is @inlinable as reasonably small.
mutating func resetBytes(in range: Range<Int>) {
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
ensureUniqueReference()
storage.resetBytes(in: range)
if slice.range.upperBound < range.upperBound {
slice.range = slice.range.lowerBound..<range.upperBound
}
}
@inlinable // This is @inlinable as reasonably small.
mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
precondition(startIndex <= subrange.lowerBound, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(subrange.lowerBound <= endIndex, "index \(subrange.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= subrange.upperBound, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(subrange.upperBound <= endIndex, "index \(subrange.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
let nsRange = NSRange(location: subrange.lowerBound, length: subrange.upperBound - subrange.lowerBound)
ensureUniqueReference()
let upper = range.upperBound
storage.replaceBytes(in: nsRange, with: bytes, length: cnt)
let resultingUpper = upper - nsRange.length + cnt
slice.range = slice.range.lowerBound..<resultingUpper
}
@inlinable // This is @inlinable as reasonably small.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
precondition(startIndex <= range.lowerBound, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(startIndex <= range.upperBound, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
precondition(range.upperBound <= endIndex, "index \(range.upperBound) is out of bounds of \(startIndex)..<\(endIndex)")
storage.copyBytes(to: pointer, from: range)
}
@inline(__always) // This should always be inlined into _Representation.hash(into:).
func hash(into hasher: inout Hasher) {
hasher.combine(count)
// Hash at most the first 80 bytes of this data.
let range = startIndex ..< Swift.min(startIndex + 80, endIndex)
storage.withUnsafeBytes(in: range) {
hasher.combine(bytes: $0)
}
}
}
// The actual storage for Data's various representations.
// Inlinability strategy: almost everything should be inlinable as forwarding the underlying implementations. (Inlining can also help avoid retain-release traffic around pulling values out of enums.)
@usableFromInline
@_frozen
internal enum _Representation {
case empty
case inline(InlineData)
case slice(InlineSlice)
case large(LargeSlice)
@inlinable // This is @inlinable as a trivial initializer.
init(_ buffer: UnsafeRawBufferPointer) {
if buffer.count == 0 {
self = .empty
} else if InlineData.canStore(count: buffer.count) {
self = .inline(InlineData(buffer))
} else if InlineSlice.canStore(count: buffer.count) {
self = .slice(InlineSlice(buffer))
} else {
self = .large(LargeSlice(buffer))
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ buffer: UnsafeRawBufferPointer, owner: AnyObject) {
if buffer.count == 0 {
self = .empty
} else if InlineData.canStore(count: buffer.count) {
self = .inline(InlineData(buffer))
} else {
let count = buffer.count
let storage = __DataStorage(bytes: UnsafeMutableRawPointer(mutating: buffer.baseAddress), length: count, copy: false, deallocator: { _, _ in
_fixLifetime(owner)
}, offset: 0)
if InlineSlice.canStore(count: count) {
self = .slice(InlineSlice(storage, count: count))
} else {
self = .large(LargeSlice(storage, count: count))
}
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(capacity: Int) {
if capacity == 0 {
self = .empty
} else if InlineData.canStore(count: capacity) {
self = .inline(InlineData())
} else if InlineSlice.canStore(count: capacity) {
self = .slice(InlineSlice(capacity: capacity))
} else {
self = .large(LargeSlice(capacity: capacity))
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(count: Int) {
if count == 0 {
self = .empty
} else if InlineData.canStore(count: count) {
self = .inline(InlineData(count: count))
} else if InlineSlice.canStore(count: count) {
self = .slice(InlineSlice(count: count))
} else {
self = .large(LargeSlice(count: count))
}
}
@inlinable // This is @inlinable as a trivial initializer.
init(_ storage: __DataStorage, count: Int) {
if count == 0 {
self = .empty
} else if InlineData.canStore(count: count) {
self = .inline(storage.withUnsafeBytes(in: 0..<count) { InlineData($0) })
} else if InlineSlice.canStore(count: count) {
self = .slice(InlineSlice(storage, count: count))
} else {
self = .large(LargeSlice(storage, count: count))
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
mutating func reserveCapacity(_ minimumCapacity: Int) {
guard minimumCapacity > 0 else { return }
switch self {
case .empty:
if InlineData.canStore(count: minimumCapacity) {
self = .inline(InlineData())
} else if InlineSlice.canStore(count: minimumCapacity) {
self = .slice(InlineSlice(capacity: minimumCapacity))
} else {
self = .large(LargeSlice(capacity: minimumCapacity))
}
case .inline(let inline):
guard minimumCapacity > inline.capacity else { return }
// we know we are going to be heap promoted
if InlineSlice.canStore(count: minimumCapacity) {
var slice = InlineSlice(inline)
slice.reserveCapacity(minimumCapacity)
self = .slice(slice)
} else {
var slice = LargeSlice(inline)
slice.reserveCapacity(minimumCapacity)
self = .large(slice)
}
case .slice(var slice):
guard minimumCapacity > slice.capacity else { return }
if InlineSlice.canStore(count: minimumCapacity) {
self = .empty
slice.reserveCapacity(minimumCapacity)
self = .slice(slice)
} else {
var large = LargeSlice(slice)
large.reserveCapacity(minimumCapacity)
self = .large(large)
}
case .large(var slice):
guard minimumCapacity > slice.capacity else { return }
self = .empty
slice.reserveCapacity(minimumCapacity)
self = .large(slice)
}
}
@inlinable // This is @inlinable as reasonably small.
var count: Int {
get {
switch self {
case .empty: return 0
case .inline(let inline): return inline.count
case .slice(let slice): return slice.count
case .large(let slice): return slice.count
}
}
set(newValue) {
// HACK: The definition of this inline function takes an inout reference to self, giving the optimizer a unique referencing guarantee.
// This allows us to avoid excessive retain-release traffic around modifying enum values, and inlining the function then avoids the additional frame.
@inline(__always)
func apply(_ representation: inout _Representation, _ newValue: Int) -> _Representation? {
switch representation {
case .empty:
if newValue == 0 {
return nil
} else if InlineData.canStore(count: newValue) {
return .inline(InlineData())
} else if InlineSlice.canStore(count: newValue) {
return .slice(InlineSlice(count: newValue))
} else {
return .large(LargeSlice(count: newValue))
}
case .inline(var inline):
if newValue == 0 {
return .empty
} else if InlineData.canStore(count: newValue) {
guard inline.count != newValue else { return nil }
inline.count = newValue
return .inline(inline)
} else if InlineSlice.canStore(count: newValue) {
var slice = InlineSlice(inline)
slice.count = newValue
return .slice(slice)
} else {
var slice = LargeSlice(inline)
slice.count = newValue
return .large(slice)
}
case .slice(var slice):
if newValue == 0 && slice.startIndex == 0 {
return .empty
} else if slice.startIndex == 0 && InlineData.canStore(count: newValue) {
return .inline(InlineData(slice, count: newValue))
} else if InlineSlice.canStore(count: newValue + slice.startIndex) {
guard slice.count != newValue else { return nil }
representation = .empty // TODO: remove this when mgottesman lands optimizations
slice.count = newValue
return .slice(slice)
} else {
var newSlice = LargeSlice(slice)
newSlice.count = newValue
return .large(newSlice)
}
case .large(var slice):
if newValue == 0 && slice.startIndex == 0 {
return .empty
} else if slice.startIndex == 0 && InlineData.canStore(count: newValue) {
return .inline(InlineData(slice, count: newValue))
} else {
guard slice.count != newValue else { return nil}
representation = .empty // TODO: remove this when mgottesman lands optimizations
slice.count = newValue
return .large(slice)
}
}
}
if let rep = apply(&self, newValue) {
self = rep
}
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withUnsafeBytes<Result>(_ apply: (UnsafeRawBufferPointer) throws -> Result) rethrows -> Result {
switch self {
case .empty:
let empty = InlineData()
return try empty.withUnsafeBytes(apply)
case .inline(let inline):
return try inline.withUnsafeBytes(apply)
case .slice(let slice):
return try slice.withUnsafeBytes(apply)
case .large(let slice):
return try slice.withUnsafeBytes(apply)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
mutating func withUnsafeMutableBytes<Result>(_ apply: (UnsafeMutableRawBufferPointer) throws -> Result) rethrows -> Result {
switch self {
case .empty:
var empty = InlineData()
return try empty.withUnsafeMutableBytes(apply)
case .inline(var inline):
defer { self = .inline(inline) }
return try inline.withUnsafeMutableBytes(apply)
case .slice(var slice):
self = .empty
defer { self = .slice(slice) }
return try slice.withUnsafeMutableBytes(apply)
case .large(var slice):
self = .empty
defer { self = .large(slice) }
return try slice.withUnsafeMutableBytes(apply)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
func withInteriorPointerReference<T>(_ work: (NSData) throws -> T) rethrows -> T {
switch self {
case .empty:
return try work(NSData())
case .inline(let inline):
return try inline.withUnsafeBytes {
return try work(NSData(bytesNoCopy: UnsafeMutableRawPointer(mutating: $0.baseAddress ?? UnsafeRawPointer(bitPattern: 0xBAD0)!), length: $0.count, freeWhenDone: false))
}
case .slice(let slice):
return try slice.storage.withInteriorPointerReference(slice.range, work)
case .large(let slice):
return try slice.storage.withInteriorPointerReference(slice.range, work)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) {
switch self {
case .empty:
var stop = false
block(UnsafeBufferPointer<UInt8>(start: nil, count: 0), 0, &stop)
case .inline(let inline):
inline.withUnsafeBytes {
var stop = false
block(UnsafeBufferPointer<UInt8>(start: $0.baseAddress?.assumingMemoryBound(to: UInt8.self), count: $0.count), 0, &stop)
}
case .slice(let slice):
slice.storage.enumerateBytes(in: slice.range, block)
case .large(let slice):
slice.storage.enumerateBytes(in: slice.range, block)
}
}
@inlinable // This is @inlinable as reasonably small.
mutating func append(contentsOf buffer: UnsafeRawBufferPointer) {
switch self {
case .empty:
self = _Representation(buffer)
case .inline(var inline):
if InlineData.canStore(count: inline.count + buffer.count) {
inline.append(contentsOf: buffer)
self = .inline(inline)
} else if InlineSlice.canStore(count: inline.count + buffer.count) {
var newSlice = InlineSlice(inline)
newSlice.append(contentsOf: buffer)
self = .slice(newSlice)
} else {
var newSlice = LargeSlice(inline)
newSlice.append(contentsOf: buffer)
self = .large(newSlice)
}
case .slice(var slice):
if InlineSlice.canStore(count: slice.range.upperBound + buffer.count) {
self = .empty
defer { self = .slice(slice) }
slice.append(contentsOf: buffer)
} else {
self = .empty
var newSlice = LargeSlice(slice)
newSlice.append(contentsOf: buffer)
self = .large(newSlice)
}
case .large(var slice):
self = .empty
defer { self = .large(slice) }
slice.append(contentsOf: buffer)
}
}
@inlinable // This is @inlinable as reasonably small.
mutating func resetBytes(in range: Range<Index>) {
switch self {
case .empty:
if range.upperBound == 0 {
self = .empty
} else if InlineData.canStore(count: range.upperBound) {
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
self = .inline(InlineData(count: range.upperBound))
} else if InlineSlice.canStore(count: range.upperBound) {
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
self = .slice(InlineSlice(count: range.upperBound))
} else {
precondition(range.lowerBound <= endIndex, "index \(range.lowerBound) is out of bounds of \(startIndex)..<\(endIndex)")
self = .large(LargeSlice(count: range.upperBound))
}
break
case .inline(var inline):
if inline.count < range.upperBound {
if InlineSlice.canStore(count: range.upperBound) {
var slice = InlineSlice(inline)
slice.resetBytes(in: range)
self = .slice(slice)
} else {
var slice = LargeSlice(inline)
slice.resetBytes(in: range)
self = .large(slice)
}
} else {
inline.resetBytes(in: range)
self = .inline(inline)
}
break
case .slice(var slice):
if InlineSlice.canStore(count: range.upperBound) {
self = .empty
slice.resetBytes(in: range)
self = .slice(slice)
} else {
self = .empty
var newSlice = LargeSlice(slice)
newSlice.resetBytes(in: range)
self = .large(newSlice)
}
break
case .large(var slice):
self = .empty
slice.resetBytes(in: range)
self = .large(slice)
}
}
@usableFromInline // This is not @inlinable as it is a non-trivial, non-generic function.
mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer?, count cnt: Int) {
switch self {
case .empty:
precondition(subrange.lowerBound == 0 && subrange.upperBound == 0, "range \(subrange) out of bounds of 0..<0")
if cnt == 0 {
return
} else if InlineData.canStore(count: cnt) {
self = .inline(InlineData(UnsafeRawBufferPointer(start: bytes, count: cnt)))
} else if InlineSlice.canStore(count: cnt) {
self = .slice(InlineSlice(UnsafeRawBufferPointer(start: bytes, count: cnt)))
} else {
self = .large(LargeSlice(UnsafeRawBufferPointer(start: bytes, count: cnt)))
}
break
case .inline(var inline):
let resultingCount = inline.count + cnt - (subrange.upperBound - subrange.lowerBound)
if resultingCount == 0 {
self = .empty
} else if InlineData.canStore(count: resultingCount) {
inline.replaceSubrange(subrange, with: bytes, count: cnt)
self = .inline(inline)
} else if InlineSlice.canStore(count: resultingCount) {
var slice = InlineSlice(inline)
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .slice(slice)
} else {
var slice = LargeSlice(inline)
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .large(slice)
}
break
case .slice(var slice):
let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound)
if slice.startIndex == 0 && resultingUpper == 0 {
self = .empty
} else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) {
self = .empty
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .inline(InlineData(slice, count: slice.count))
} else if InlineSlice.canStore(count: resultingUpper) {
self = .empty
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .slice(slice)
} else {
self = .empty
var newSlice = LargeSlice(slice)
newSlice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .large(newSlice)
}
case .large(var slice):
let resultingUpper = slice.endIndex + cnt - (subrange.upperBound - subrange.lowerBound)
if slice.startIndex == 0 && resultingUpper == 0 {
self = .empty
} else if slice.startIndex == 0 && InlineData.canStore(count: resultingUpper) {
var inline = InlineData(count: resultingUpper)
inline.withUnsafeMutableBytes { inlineBuffer in
if cnt > 0 {
inlineBuffer.baseAddress?.advanced(by: subrange.lowerBound).copyMemory(from: bytes!, byteCount: cnt)
}
slice.withUnsafeBytes { buffer in
if subrange.lowerBound > 0 {
inlineBuffer.baseAddress?.copyMemory(from: buffer.baseAddress!, byteCount: subrange.lowerBound)
}
if subrange.upperBound < resultingUpper {
inlineBuffer.baseAddress?.advanced(by: subrange.upperBound).copyMemory(from: buffer.baseAddress!.advanced(by: subrange.upperBound), byteCount: resultingUpper - subrange.upperBound)
}
}
}
self = .inline(inline)
} else if InlineSlice.canStore(count: slice.startIndex) && InlineSlice.canStore(count: resultingUpper) {
self = .empty
var newSlice = InlineSlice(slice)
newSlice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .slice(newSlice)
} else {
self = .empty
slice.replaceSubrange(subrange, with: bytes, count: cnt)
self = .large(slice)
}
}
}
@inlinable // This is @inlinable as trivially forwarding.
subscript(index: Index) -> UInt8 {
get {
switch self {
case .empty: preconditionFailure("index \(index) out of range of 0")
case .inline(let inline): return inline[index]
case .slice(let slice): return slice[index]
case .large(let slice): return slice[index]
}
}
set(newValue) {
switch self {
case .empty: preconditionFailure("index \(index) out of range of 0")
case .inline(var inline):
inline[index] = newValue
self = .inline(inline)
case .slice(var slice):
self = .empty
slice[index] = newValue
self = .slice(slice)
case .large(var slice):
self = .empty
slice[index] = newValue
self = .large(slice)
}
}
}
@inlinable // This is @inlinable as reasonably small.
subscript(bounds: Range<Index>) -> Data {
get {
switch self {
case .empty:
precondition(bounds.lowerBound == 0 && (bounds.upperBound - bounds.lowerBound) == 0, "Range \(bounds) out of bounds 0..<0")
return Data()
case .inline(let inline):
precondition(bounds.upperBound <= inline.count, "Range \(bounds) out of bounds 0..<\(inline.count)")
if bounds.lowerBound == 0 {
var newInline = inline
newInline.count = bounds.upperBound
return Data(representation: .inline(newInline))
} else {
return Data(representation: .slice(InlineSlice(inline, range: bounds)))
}
case .slice(let slice):
precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)")
precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)")
precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)")
precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)")
if bounds.lowerBound == 0 && bounds.upperBound == 0 {
return Data()
} else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.count) {
return Data(representation: .inline(InlineData(slice, count: bounds.count)))
} else {
var newSlice = slice
newSlice.range = bounds
return Data(representation: .slice(newSlice))
}
case .large(let slice):
precondition(slice.startIndex <= bounds.lowerBound, "Range \(bounds) out of bounds \(slice.range)")
precondition(bounds.lowerBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)")
precondition(slice.startIndex <= bounds.upperBound, "Range \(bounds) out of bounds \(slice.range)")
precondition(bounds.upperBound <= slice.endIndex, "Range \(bounds) out of bounds \(slice.range)")
if bounds.lowerBound == 0 && bounds.upperBound == 0 {
return Data()
} else if bounds.lowerBound == 0 && InlineData.canStore(count: bounds.upperBound) {
return Data(representation: .inline(InlineData(slice, count: bounds.upperBound)))
} else if InlineSlice.canStore(count: bounds.lowerBound) && InlineSlice.canStore(count: bounds.upperBound) {
return Data(representation: .slice(InlineSlice(slice, range: bounds)))
} else {
var newSlice = slice
newSlice.slice = RangeReference(bounds)
return Data(representation: .large(newSlice))
}
}
}
}
@inlinable // This is @inlinable as trivially forwarding.
var startIndex: Int {
switch self {
case .empty: return 0
case .inline: return 0
case .slice(let slice): return slice.startIndex
case .large(let slice): return slice.startIndex
}
}
@inlinable // This is @inlinable as trivially forwarding.
var endIndex: Int {
switch self {
case .empty: return 0
case .inline(let inline): return inline.count
case .slice(let slice): return slice.endIndex
case .large(let slice): return slice.endIndex
}
}
@inlinable // This is @inlinable as trivially forwarding.
func bridgedReference() -> NSData {
switch self {
case .empty: return NSData()
case .inline(let inline):
return inline.withUnsafeBytes {
return NSData(bytes: $0.baseAddress, length: $0.count)
}
case .slice(let slice):
return slice.bridgedReference()
case .large(let slice):
return slice.bridgedReference()
}
}
@inlinable // This is @inlinable as trivially forwarding.
func copyBytes(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
switch self {
case .empty:
precondition(range.lowerBound == 0 && range.upperBound == 0, "Range \(range) out of bounds 0..<0")
return
case .inline(let inline):
inline.copyBytes(to: pointer, from: range)
break
case .slice(let slice):
slice.copyBytes(to: pointer, from: range)
case .large(let slice):
slice.copyBytes(to: pointer, from: range)
}
}
@inline(__always) // This should always be inlined into Data.hash(into:).
func hash(into hasher: inout Hasher) {
switch self {
case .empty:
hasher.combine(0)
case .inline(let inline):
inline.hash(into: &hasher)
case .slice(let slice):
slice.hash(into: &hasher)
case .large(let large):
large.hash(into: &hasher)
}
}
}
@usableFromInline internal var _representation: _Representation
// A standard or custom deallocator for `Data`.
///
/// When creating a `Data` with the no-copy initializer, you may specify a `Data.Deallocator` to customize the behavior of how the backing store is deallocated.
public enum Deallocator {
/// Use a virtual memory deallocator.
#if !DEPLOYMENT_RUNTIME_SWIFT
case virtualMemory
#endif
/// Use `munmap`.
case unmap
/// Use `free`.
case free
/// Do nothing upon deallocation.
case none
/// A custom deallocator.
case custom((UnsafeMutableRawPointer, Int) -> Void)
@usableFromInline internal var _deallocator : ((UnsafeMutableRawPointer, Int) -> Void) {
#if DEPLOYMENT_RUNTIME_SWIFT
switch self {
case .unmap:
return { __NSDataInvokeDeallocatorUnmap($0, $1) }
case .free:
return { __NSDataInvokeDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return b
}
#else
switch self {
case .virtualMemory:
return { NSDataDeallocatorVM($0, $1) }
case .unmap:
return { NSDataDeallocatorUnmap($0, $1) }
case .free:
return { NSDataDeallocatorFree($0, $1) }
case .none:
return { _, _ in }
case .custom(let b):
return b
}
#endif
}
}
// MARK: -
// MARK: Init methods
/// Initialize a `Data` with copied memory content.
///
/// - parameter bytes: A pointer to the memory. It will be copied.
/// - parameter count: The number of bytes to copy.
@inlinable // This is @inlinable as a trivial initializer.
public init(bytes: UnsafeRawPointer, count: Int) {
_representation = _Representation(UnsafeRawBufferPointer(start: bytes, count: count))
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
@inlinable // This is @inlinable as a trivial, generic initializer.
public init<SourceType>(buffer: UnsafeBufferPointer<SourceType>) {
_representation = _Representation(UnsafeRawBufferPointer(buffer))
}
/// Initialize a `Data` with copied memory content.
///
/// - parameter buffer: A buffer pointer to copy. The size is calculated from `SourceType` and `buffer.count`.
@inlinable // This is @inlinable as a trivial, generic initializer.
public init<SourceType>(buffer: UnsafeMutableBufferPointer<SourceType>) {
_representation = _Representation(UnsafeRawBufferPointer(buffer))
}
/// Initialize a `Data` with a repeating byte pattern
///
/// - parameter repeatedValue: A byte to initialize the pattern
/// - parameter count: The number of bytes the data initially contains initialized to the repeatedValue
@inlinable // This is @inlinable as a convenience initializer.
public init(repeating repeatedValue: UInt8, count: Int) {
self.init(count: count)
if count > 0 {
withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) -> Void in
memset(buffer.baseAddress!, Int32(repeatedValue), buffer.count)
}
}
}
/// Initialize a `Data` with the specified size.
///
/// This initializer doesn't necessarily allocate the requested memory right away. `Data` allocates additional memory as needed, so `capacity` simply establishes the initial capacity. When it does allocate the initial memory, though, it allocates the specified amount.
///
/// This method sets the `count` of the data to 0.
///
/// If the capacity specified in `capacity` is greater than four memory pages in size, this may round the amount of requested memory up to the nearest full page.
///
/// - parameter capacity: The size of the data.
@inlinable // This is @inlinable as a trivial initializer.
public init(capacity: Int) {
_representation = _Representation(capacity: capacity)
}
/// Initialize a `Data` with the specified count of zeroed bytes.
///
/// - parameter count: The number of bytes the data initially contains.
@inlinable // This is @inlinable as a trivial initializer.
public init(count: Int) {
_representation = _Representation(count: count)
}
/// Initialize an empty `Data`.
@inlinable // This is @inlinable as a trivial initializer.
public init() {
_representation = .empty
}
/// Initialize a `Data` without copying the bytes.
///
/// If the result is mutated and is not a unique reference, then the `Data` will still follow copy-on-write semantics. In this case, the copy will use its own deallocator. Therefore, it is usually best to only use this initializer when you either enforce immutability with `let` or ensure that no other references to the underlying data are formed.
/// - parameter bytes: A pointer to the bytes.
/// - parameter count: The size of the bytes.
/// - parameter deallocator: Specifies the mechanism to free the indicated buffer, or `.none`.
@inlinable // This is @inlinable as a trivial initializer.
public init(bytesNoCopy bytes: UnsafeMutableRawPointer, count: Int, deallocator: Deallocator) {
let whichDeallocator = deallocator._deallocator
if count == 0 {
deallocator._deallocator(bytes, count)
_representation = .empty
} else {
_representation = _Representation(__DataStorage(bytes: bytes, length: count, copy: false, deallocator: whichDeallocator, offset: 0), count: count)
}
}
/// Initialize a `Data` with the contents of a `URL`.
///
/// - parameter url: The `URL` to read.
/// - parameter options: Options for the read operation. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if `url` cannot be read.
@inlinable // This is @inlinable as a convenience initializer.
public init(contentsOf url: __shared URL, options: Data.ReadingOptions = []) throws {
let d = try NSData(contentsOf: url, options: ReadingOptions(rawValue: options.rawValue))
self.init(bytes: d.bytes, count: d.length)
}
/// Initialize a `Data` from a Base-64 encoded String using the given options.
///
/// Returns nil when the input is not recognized as valid Base-64.
/// - parameter base64String: The string to parse.
/// - parameter options: Encoding options. Default value is `[]`.
@inlinable // This is @inlinable as a convenience initializer.
public init?(base64Encoded base64String: __shared String, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64String, options: Base64DecodingOptions(rawValue: options.rawValue)) {
self.init(bytes: d.bytes, count: d.length)
} else {
return nil
}
}
/// Initialize a `Data` from a Base-64, UTF-8 encoded `Data`.
///
/// Returns nil when the input is not recognized as valid Base-64.
///
/// - parameter base64Data: Base-64, UTF-8 encoded input data.
/// - parameter options: Decoding options. Default value is `[]`.
@inlinable // This is @inlinable as a convenience initializer.
public init?(base64Encoded base64Data: __shared Data, options: Data.Base64DecodingOptions = []) {
if let d = NSData(base64Encoded: base64Data, options: Base64DecodingOptions(rawValue: options.rawValue)) {
self.init(bytes: d.bytes, count: d.length)
} else {
return nil
}
}
/// Initialize a `Data` by adopting a reference type.
///
/// You can use this initializer to create a `struct Data` that wraps a `class NSData`. `struct Data` will use the `class NSData` for all operations. Other initializers (including casting using `as Data`) may choose to hold a reference or not, based on a what is the most efficient representation.
///
/// If the resulting value is mutated, then `Data` will invoke the `mutableCopy()` function on the reference to copy the contents. You may customize the behavior of that function if you wish to return a specialized mutable subclass.
///
/// - parameter reference: The instance of `NSData` that you wish to wrap. This instance will be copied by `struct Data`.
public init(referencing reference: __shared NSData) {
// This is not marked as inline because _providesConcreteBacking would need to be marked as usable from inline however that is a dynamic lookup in objc contexts.
let length = reference.length
if length == 0 {
_representation = .empty
} else {
#if DEPLOYMENT_RUNTIME_SWIFT
let providesConcreteBacking = reference._providesConcreteBacking()
#else
let providesConcreteBacking = (reference as AnyObject)._providesConcreteBacking?() ?? false
#endif
if providesConcreteBacking {
_representation = _Representation(__DataStorage(immutableReference: reference.copy() as! NSData, offset: 0), count: length)
} else {
_representation = _Representation(__DataStorage(customReference: reference.copy() as! NSData, offset: 0), count: length)
}
}
}
// slightly faster paths for common sequences
@inlinable // This is @inlinable as an important generic funnel point, despite being a non-trivial initializer.
public init<S: Sequence>(_ elements: S) where S.Element == UInt8 {
// If the sequence is already contiguous, access the underlying raw memory directly.
if let contiguous = elements as? ContiguousBytes {
_representation = contiguous.withUnsafeBytes { return _Representation($0) }
return
}
// The sequence might still be able to provide direct access to typed memory.
// NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences.
let representation = elements.withContiguousStorageIfAvailable {
return _Representation(UnsafeRawBufferPointer($0))
}
if let representation = representation {
_representation = representation
} else {
// Dummy assignment so we can capture below.
_representation = _Representation(capacity: 0)
// Copy as much as we can in one shot from the sequence.
let underestimatedCount = Swift.max(elements.underestimatedCount, 1)
_withStackOrHeapBuffer(underestimatedCount) { (buffer) in
// In order to copy from the sequence, we have to bind the buffer to UInt8.
// This is safe since we'll copy out of this buffer as raw memory later.
let capacity = buffer.pointee.capacity
let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity)
var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity))
// Copy the contents of buffer...
_representation = _Representation(UnsafeRawBufferPointer(start: base, count: endIndex))
// ... and append the rest byte-wise, buffering through an InlineData.
var buffer = InlineData()
while let element = iter.next() {
buffer.append(byte: element)
if buffer.count == buffer.capacity {
buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
buffer.count = 0
}
}
// If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them.
if buffer.count > 0 {
buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
buffer.count = 0
}
}
}
}
@available(swift, introduced: 4.2)
@available(swift, deprecated: 5, renamed: "init(_:)")
public init<S: Sequence>(bytes elements: S) where S.Iterator.Element == UInt8 {
self.init(elements)
}
@available(swift, obsoleted: 4.2)
public init(bytes: Array<UInt8>) {
self.init(bytes)
}
@available(swift, obsoleted: 4.2)
public init(bytes: ArraySlice<UInt8>) {
self.init(bytes)
}
@inlinable // This is @inlinable as a trivial initializer.
internal init(representation: _Representation) {
_representation = representation
}
// -----------------------------------
// MARK: - Properties and Functions
@inlinable // This is @inlinable as trivially forwarding.
public mutating func reserveCapacity(_ minimumCapacity: Int) {
_representation.reserveCapacity(minimumCapacity)
}
/// The number of bytes in the data.
@inlinable // This is @inlinable as trivially forwarding.
public var count: Int {
get {
return _representation.count
}
set(newValue) {
precondition(newValue >= 0, "count must not be negative")
_representation.count = newValue
}
}
@inlinable // This is @inlinable as trivially computable.
public var regions: CollectionOfOne<Data> {
return CollectionOfOne(self)
}
/// Access the bytes in the data.
///
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
@available(swift, deprecated: 5, message: "use `withUnsafeBytes<R>(_: (UnsafeRawBufferPointer) throws -> R) rethrows -> R` instead")
public func withUnsafeBytes<ResultType, ContentType>(_ body: (UnsafePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
return try _representation.withUnsafeBytes {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public func withUnsafeBytes<ResultType>(_ body: (UnsafeRawBufferPointer) throws -> ResultType) rethrows -> ResultType {
return try _representation.withUnsafeBytes(body)
}
/// Mutate the bytes in the data.
///
/// This function assumes that you are mutating the contents.
/// - warning: The byte pointer argument should not be stored and used outside of the lifetime of the call to the closure.
@available(swift, deprecated: 5, message: "use `withUnsafeMutableBytes<R>(_: (UnsafeMutableRawBufferPointer) throws -> R) rethrows -> R` instead")
public mutating func withUnsafeMutableBytes<ResultType, ContentType>(_ body: (UnsafeMutablePointer<ContentType>) throws -> ResultType) rethrows -> ResultType {
return try _representation.withUnsafeMutableBytes {
return try body($0.baseAddress?.assumingMemoryBound(to: ContentType.self) ?? UnsafeMutablePointer<ContentType>(bitPattern: 0xBAD0)!)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public mutating func withUnsafeMutableBytes<ResultType>(_ body: (UnsafeMutableRawBufferPointer) throws -> ResultType) rethrows -> ResultType {
return try _representation.withUnsafeMutableBytes(body)
}
// MARK: -
// MARK: Copy Bytes
/// Copy the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter count: The number of bytes to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold `count` bytes.
@inlinable // This is @inlinable as trivially forwarding.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, count: Int) {
precondition(count >= 0, "count of bytes to copy must not be negative")
if count == 0 { return }
_copyBytesHelper(to: UnsafeMutableRawPointer(pointer), from: startIndex..<(startIndex + count))
}
@inlinable // This is @inlinable as trivially forwarding.
internal func _copyBytesHelper(to pointer: UnsafeMutableRawPointer, from range: Range<Int>) {
if range.upperBound - range.lowerBound == 0 { return }
_representation.copyBytes(to: pointer, from: range)
}
/// Copy a subset of the contents of the data to a pointer.
///
/// - parameter pointer: A pointer to the buffer you wish to copy the bytes into.
/// - parameter range: The range in the `Data` to copy.
/// - warning: This method does not verify that the contents at pointer have enough space to hold the required number of bytes.
@inlinable // This is @inlinable as trivially forwarding.
public func copyBytes(to pointer: UnsafeMutablePointer<UInt8>, from range: Range<Index>) {
_copyBytesHelper(to: pointer, from: range)
}
// Copy the contents of the data into a buffer.
///
/// This function copies the bytes in `range` from the data into the buffer. If the count of the `range` is greater than `MemoryLayout<DestinationType>.stride * buffer.count` then the first N bytes will be copied into the buffer.
/// - precondition: The range must be within the bounds of the data. Otherwise `fatalError` is called.
/// - parameter buffer: A buffer to copy the data into.
/// - parameter range: A range in the data to copy into the buffer. If the range is empty, this function will return 0 without copying anything. If the range is nil, as much data as will fit into `buffer` is copied.
/// - returns: Number of bytes copied into the destination buffer.
@inlinable // This is @inlinable as generic and reasonably small.
public func copyBytes<DestinationType>(to buffer: UnsafeMutableBufferPointer<DestinationType>, from range: Range<Index>? = nil) -> Int {
let cnt = count
guard cnt > 0 else { return 0 }
let copyRange : Range<Index>
if let r = range {
guard !r.isEmpty else { return 0 }
copyRange = r.lowerBound..<(r.lowerBound + Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, r.upperBound - r.lowerBound))
} else {
copyRange = 0..<Swift.min(buffer.count * MemoryLayout<DestinationType>.stride, cnt)
}
guard !copyRange.isEmpty else { return 0 }
_copyBytesHelper(to: buffer.baseAddress!, from: copyRange)
return copyRange.upperBound - copyRange.lowerBound
}
// MARK: -
#if !DEPLOYMENT_RUNTIME_SWIFT
private func _shouldUseNonAtomicWriteReimplementation(options: Data.WritingOptions = []) -> Bool {
// Avoid a crash that happens on OS X 10.11.x and iOS 9.x or before when writing a bridged Data non-atomically with Foundation's standard write() implementation.
if !options.contains(.atomic) {
#if os(macOS)
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber10_11_Max)
#else
return NSFoundationVersionNumber <= Double(NSFoundationVersionNumber_iOS_9_x_Max)
#endif
} else {
return false
}
}
#endif
/// Write the contents of the `Data` to a location.
///
/// - parameter url: The location to write the data into.
/// - parameter options: Options for writing the data. Default value is `[]`.
/// - throws: An error in the Cocoa domain, if there is an error writing to the `URL`.
public func write(to url: URL, options: Data.WritingOptions = []) throws {
// this should not be marked as inline since in objc contexts we correct atomicity via _shouldUseNonAtomicWriteReimplementation
try _representation.withInteriorPointerReference {
#if DEPLOYMENT_RUNTIME_SWIFT
try $0.write(to: url, options: WritingOptions(rawValue: options.rawValue))
#else
if _shouldUseNonAtomicWriteReimplementation(options: options) {
var error: NSError? = nil
guard __NSDataWriteToURL($0, url, options, &error) else { throw error! }
} else {
try $0.write(to: url, options: options)
}
#endif
}
}
// MARK: -
/// Find the given `Data` in the content of this `Data`.
///
/// - parameter dataToFind: The data to be searched for.
/// - parameter options: Options for the search. Default value is `[]`.
/// - parameter range: The range of this data in which to perform the search. Default value is `nil`, which means the entire content of this data.
/// - returns: A `Range` specifying the location of the found data, or nil if a match could not be found.
/// - precondition: `range` must be in the bounds of the Data.
public func range(of dataToFind: Data, options: Data.SearchOptions = [], in range: Range<Index>? = nil) -> Range<Index>? {
let nsRange : NSRange
if let r = range {
nsRange = NSRange(location: r.lowerBound - startIndex, length: r.upperBound - r.lowerBound)
} else {
nsRange = NSRange(location: 0, length: count)
}
let result = _representation.withInteriorPointerReference {
$0.range(of: dataToFind, options: options, in: nsRange)
}
if result.location == NSNotFound {
return nil
}
return (result.location + startIndex)..<((result.location + startIndex) + result.length)
}
/// Enumerate the contents of the data.
///
/// In some cases, (for example, a `Data` backed by a `dispatch_data_t`, the bytes may be stored discontiguously. In those cases, this function invokes the closure for each contiguous region of bytes.
/// - parameter block: The closure to invoke for each region of data. You may stop the enumeration by setting the `stop` parameter to `true`.
@available(swift, deprecated: 5, message: "use `regions` or `for-in` instead")
public func enumerateBytes(_ block: (_ buffer: UnsafeBufferPointer<UInt8>, _ byteIndex: Index, _ stop: inout Bool) -> Void) {
_representation.enumerateBytes(block)
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
internal mutating func _append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
if buffer.isEmpty { return }
_representation.append(contentsOf: UnsafeRawBufferPointer(buffer))
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public mutating func append(_ bytes: UnsafePointer<UInt8>, count: Int) {
if count == 0 { return }
_append(UnsafeBufferPointer(start: bytes, count: count))
}
public mutating func append(_ other: Data) {
guard other.count > 0 else { return }
other.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
_representation.append(contentsOf: buffer)
}
}
/// Append a buffer of bytes to the data.
///
/// - parameter buffer: The buffer of bytes to append. The size is calculated from `SourceType` and `buffer.count`.
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public mutating func append<SourceType>(_ buffer : UnsafeBufferPointer<SourceType>) {
_append(buffer)
}
@inlinable // This is @inlinable as trivially forwarding.
public mutating func append(contentsOf bytes: [UInt8]) {
bytes.withUnsafeBufferPointer { (buffer: UnsafeBufferPointer<UInt8>) -> Void in
_append(buffer)
}
}
@inlinable // This is @inlinable as an important generic funnel point, despite being non-trivial.
public mutating func append<S: Sequence>(contentsOf elements: S) where S.Element == Element {
// If the sequence is already contiguous, access the underlying raw memory directly.
if let contiguous = elements as? ContiguousBytes {
contiguous.withUnsafeBytes {
_representation.append(contentsOf: $0)
}
return
}
// The sequence might still be able to provide direct access to typed memory.
// NOTE: It's safe to do this because we're already guarding on S's element as `UInt8`. This would not be safe on arbitrary sequences.
var appended = false
elements.withContiguousStorageIfAvailable {
_representation.append(contentsOf: UnsafeRawBufferPointer($0))
appended = true
}
guard !appended else { return }
// The sequence is really not contiguous.
// Copy as much as we can in one shot.
let underestimatedCount = Swift.max(elements.underestimatedCount, 1)
_withStackOrHeapBuffer(underestimatedCount) { (buffer) in
// In order to copy from the sequence, we have to bind the temporary buffer to `UInt8`.
// This is safe since we're the only owners of the buffer and we copy out as raw memory below anyway.
let capacity = buffer.pointee.capacity
let base = buffer.pointee.memory.bindMemory(to: UInt8.self, capacity: capacity)
var (iter, endIndex) = elements._copyContents(initializing: UnsafeMutableBufferPointer(start: base, count: capacity))
// Copy the contents of the buffer...
_representation.append(contentsOf: UnsafeRawBufferPointer(start: base, count: endIndex))
// ... and append the rest byte-wise, buffering through an InlineData.
var buffer = InlineData()
while let element = iter.next() {
buffer.append(byte: element)
if buffer.count == buffer.capacity {
buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
buffer.count = 0
}
}
// If we've still got bytes left in the buffer (i.e. the loop ended before we filled up the buffer and cleared it out), append them.
if buffer.count > 0 {
buffer.withUnsafeBytes { _representation.append(contentsOf: $0) }
buffer.count = 0
}
}
}
// MARK: -
/// Set a region of the data to `0`.
///
/// If `range` exceeds the bounds of the data, then the data is resized to fit.
/// - parameter range: The range in the data to set to `0`.
@inlinable // This is @inlinable as trivially forwarding.
public mutating func resetBytes(in range: Range<Index>) {
// it is worth noting that the range here may be out of bounds of the Data itself (which triggers a growth)
precondition(range.lowerBound >= 0, "Ranges must not be negative bounds")
precondition(range.upperBound >= 0, "Ranges must not be negative bounds")
_representation.resetBytes(in: range)
}
/// Replace a region of bytes in the data with new data.
///
/// This will resize the data if required, to fit the entire contents of `data`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace. If `subrange.lowerBound == data.count && subrange.count == 0` then this operation is an append.
/// - parameter data: The replacement data.
@inlinable // This is @inlinable as trivially forwarding.
public mutating func replaceSubrange(_ subrange: Range<Index>, with data: Data) {
data.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
_representation.replaceSubrange(subrange, with: buffer.baseAddress, count: buffer.count)
}
}
/// Replace a region of bytes in the data with new bytes from a buffer.
///
/// This will resize the data if required, to fit the entire contents of `buffer`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter buffer: The replacement bytes.
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public mutating func replaceSubrange<SourceType>(_ subrange: Range<Index>, with buffer: UnsafeBufferPointer<SourceType>) {
guard !buffer.isEmpty else { return }
replaceSubrange(subrange, with: buffer.baseAddress!, count: buffer.count * MemoryLayout<SourceType>.stride)
}
/// Replace a region of bytes in the data with new bytes from a collection.
///
/// This will resize the data if required, to fit the entire contents of `newElements`.
///
/// - precondition: The bounds of `subrange` must be valid indices of the collection.
/// - parameter subrange: The range in the data to replace.
/// - parameter newElements: The replacement bytes.
@inlinable // This is @inlinable as generic and reasonably small.
public mutating func replaceSubrange<ByteCollection : Collection>(_ subrange: Range<Index>, with newElements: ByteCollection) where ByteCollection.Iterator.Element == Data.Iterator.Element {
let totalCount = Int(newElements.count)
_withStackOrHeapBuffer(totalCount) { conditionalBuffer in
let buffer = UnsafeMutableBufferPointer(start: conditionalBuffer.pointee.memory.assumingMemoryBound(to: UInt8.self), count: totalCount)
var (iterator, index) = newElements._copyContents(initializing: buffer)
while let byte = iterator.next() {
buffer[index] = byte
index = buffer.index(after: index)
}
replaceSubrange(subrange, with: conditionalBuffer.pointee.memory, count: totalCount)
}
}
@inlinable // This is @inlinable as trivially forwarding.
public mutating func replaceSubrange(_ subrange: Range<Index>, with bytes: UnsafeRawPointer, count cnt: Int) {
_representation.replaceSubrange(subrange, with: bytes, count: cnt)
}
/// Return a new copy of the data in a specified range.
///
/// - parameter range: The range to copy.
public func subdata(in range: Range<Index>) -> Data {
if isEmpty || range.upperBound - range.lowerBound == 0 {
return Data()
}
let slice = self[range]
return slice.withUnsafeBytes { (buffer: UnsafeRawBufferPointer) -> Data in
return Data(bytes: buffer.baseAddress!, count: buffer.count)
}
}
// MARK: -
//
/// Returns a Base-64 encoded string.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded string.
@inlinable // This is @inlinable as trivially forwarding.
public func base64EncodedString(options: Data.Base64EncodingOptions = []) -> String {
return _representation.withInteriorPointerReference {
return $0.base64EncodedString(options: options)
}
}
/// Returns a Base-64 encoded `Data`.
///
/// - parameter options: The options to use for the encoding. Default value is `[]`.
/// - returns: The Base-64 encoded data.
@inlinable // This is @inlinable as trivially forwarding.
public func base64EncodedData(options: Data.Base64EncodingOptions = []) -> Data {
return _representation.withInteriorPointerReference {
return $0.base64EncodedData(options: options)
}
}
// MARK: -
//
/// The hash value for the data.
@inline(never) // This is not inlinable as emission into clients could cause cross-module inconsistencies if they are not all recompiled together.
public func hash(into hasher: inout Hasher) {
_representation.hash(into: &hasher)
}
public func advanced(by amount: Int) -> Data {
let length = count - amount
precondition(length > 0)
return withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Data in
return Data(bytes: ptr.baseAddress!.advanced(by: amount), count: length)
}
}
// MARK: -
// MARK: -
// MARK: Index and Subscript
/// Sets or returns the byte at the specified index.
@inlinable // This is @inlinable as trivially forwarding.
public subscript(index: Index) -> UInt8 {
get {
return _representation[index]
}
set(newValue) {
_representation[index] = newValue
}
}
@inlinable // This is @inlinable as trivially forwarding.
public subscript(bounds: Range<Index>) -> Data {
get {
return _representation[bounds]
}
set {
replaceSubrange(bounds, with: newValue)
}
}
@inlinable // This is @inlinable as a generic, trivially forwarding function.
public subscript<R: RangeExpression>(_ rangeExpression: R) -> Data
where R.Bound: FixedWidthInteger {
get {
let lower = R.Bound(startIndex)
let upper = R.Bound(endIndex)
let range = rangeExpression.relative(to: lower..<upper)
let start = Int(range.lowerBound)
let end = Int(range.upperBound)
let r: Range<Int> = start..<end
return _representation[r]
}
set {
let lower = R.Bound(startIndex)
let upper = R.Bound(endIndex)
let range = rangeExpression.relative(to: lower..<upper)
let start = Int(range.lowerBound)
let end = Int(range.upperBound)
let r: Range<Int> = start..<end
replaceSubrange(r, with: newValue)
}
}
/// The start `Index` in the data.
@inlinable // This is @inlinable as trivially forwarding.
public var startIndex: Index {
get {
return _representation.startIndex
}
}
/// The end `Index` into the data.
///
/// This is the "one-past-the-end" position, and will always be equal to the `count`.
@inlinable // This is @inlinable as trivially forwarding.
public var endIndex: Index {
get {
return _representation.endIndex
}
}
@inlinable // This is @inlinable as trivially computable.
public func index(before i: Index) -> Index {
return i - 1
}
@inlinable // This is @inlinable as trivially computable.
public func index(after i: Index) -> Index {
return i + 1
}
@inlinable // This is @inlinable as trivially computable.
public var indices: Range<Int> {
get {
return startIndex..<endIndex
}
}
@inlinable // This is @inlinable as a fast-path for emitting into generic Sequence usages.
public func _copyContents(initializing buffer: UnsafeMutableBufferPointer<UInt8>) -> (Iterator, UnsafeMutableBufferPointer<UInt8>.Index) {
guard !isEmpty else { return (makeIterator(), buffer.startIndex) }
let cnt = Swift.min(count, buffer.count)
if cnt > 0 {
withUnsafeBytes { (bytes: UnsafeRawBufferPointer) in
_ = memcpy(UnsafeMutableRawPointer(buffer.baseAddress!), bytes.baseAddress!, cnt)
}
}
return (Iterator(self, at: startIndex + cnt), buffer.index(buffer.startIndex, offsetBy: cnt))
}
/// An iterator over the contents of the data.
///
/// The iterator will increment byte-by-byte.
@inlinable // This is @inlinable as trivially computable.
public func makeIterator() -> Data.Iterator {
return Iterator(self, at: startIndex)
}
public struct Iterator : IteratorProtocol {
@usableFromInline
internal typealias Buffer = (
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8,
UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
@usableFromInline internal let _data: Data
@usableFromInline internal var _buffer: Buffer
@usableFromInline internal var _idx: Data.Index
@usableFromInline internal let _endIdx: Data.Index
@usableFromInline // This is @usableFromInline as a non-trivial initializer.
internal init(_ data: Data, at loc: Data.Index) {
// The let vars prevent this from being marked as @inlinable
_data = data
_buffer = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
_idx = loc
_endIdx = data.endIndex
let bufferSize = MemoryLayout<Buffer>.size
Swift.withUnsafeMutableBytes(of: &_buffer) {
let ptr = $0.bindMemory(to: UInt8.self)
let bufferIdx = (loc - data.startIndex) % bufferSize
data.copyBytes(to: ptr, from: (loc - bufferIdx)..<(data.endIndex - (loc - bufferIdx) > bufferSize ? (loc - bufferIdx) + bufferSize : data.endIndex))
}
}
public mutating func next() -> UInt8? {
let idx = _idx
let bufferSize = MemoryLayout<Buffer>.size
guard idx < _endIdx else { return nil }
_idx += 1
let bufferIdx = (idx - _data.startIndex) % bufferSize
if bufferIdx == 0 {
var buffer = _buffer
Swift.withUnsafeMutableBytes(of: &buffer) {
let ptr = $0.bindMemory(to: UInt8.self)
// populate the buffer
_data.copyBytes(to: ptr, from: idx..<(_endIdx - idx > bufferSize ? idx + bufferSize : _endIdx))
}
_buffer = buffer
}
return Swift.withUnsafeMutableBytes(of: &_buffer) {
let ptr = $0.bindMemory(to: UInt8.self)
return ptr[bufferIdx]
}
}
}
// MARK: -
//
@available(*, unavailable, renamed: "count")
public var length: Int {
get { fatalError() }
set { fatalError() }
}
@available(*, unavailable, message: "use withUnsafeBytes instead")
public var bytes: UnsafeRawPointer { fatalError() }
@available(*, unavailable, message: "use withUnsafeMutableBytes instead")
public var mutableBytes: UnsafeMutableRawPointer { fatalError() }
/// Returns `true` if the two `Data` arguments are equal.
@inlinable // This is @inlinable as emission into clients is safe -- the concept of equality on Data will not change.
public static func ==(d1 : Data, d2 : Data) -> Bool {
let length1 = d1.count
if length1 != d2.count {
return false
}
if length1 > 0 {
return d1.withUnsafeBytes { (b1: UnsafeRawBufferPointer) in
return d2.withUnsafeBytes { (b2: UnsafeRawBufferPointer) in
return memcmp(b1.baseAddress!, b2.baseAddress!, b2.count) == 0
}
}
}
return true
}
}
extension Data : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
/// A human-readable description for the data.
public var description: String {
return "\(self.count) bytes"
}
/// A human-readable debug description for the data.
public var debugDescription: String {
return self.description
}
public var customMirror: Mirror {
let nBytes = self.count
var children: [(label: String?, value: Any)] = []
children.append((label: "count", value: nBytes))
self.withUnsafeBytes { (bytes : UnsafeRawBufferPointer) in
children.append((label: "pointer", value: bytes.baseAddress!))
}
// Minimal size data is output as an array
if nBytes < 64 {
children.append((label: "bytes", value: Array(self[startIndex..<Swift.min(nBytes + startIndex, endIndex)])))
}
let m = Mirror(self, children:children, displayStyle: Mirror.DisplayStyle.struct)
return m
}
}
extension Data {
@available(*, unavailable, renamed: "copyBytes(to:count:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, length: Int) { }
@available(*, unavailable, renamed: "copyBytes(to:from:)")
public func getBytes<UnsafeMutablePointerVoid: _Pointer>(_ buffer: UnsafeMutablePointerVoid, range: NSRange) { }
}
/// Provides bridging functionality for struct Data to class NSData and vice-versa.
extension Data : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSData {
return _representation.bridgedReference()
}
public static func _forceBridgeFromObjectiveC(_ input: NSData, result: inout Data?) {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSData, result: inout Data?) -> Bool {
// We must copy the input because it might be mutable; just like storing a value type in ObjC
result = Data(referencing: input)
return true
}
// @_effects(readonly)
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSData?) -> Data {
guard let src = source else { return Data() }
return Data(referencing: src)
}
}
extension NSData : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(Data._unconditionallyBridgeFromObjectiveC(self))
}
}
extension Data : Codable {
public init(from decoder: Decoder) throws {
var container = try decoder.unkeyedContainer()
// It's more efficient to pre-allocate the buffer if we can.
if let count = container.count {
self.init(count: count)
// Loop only until count, not while !container.isAtEnd, in case count is underestimated (this is misbehavior) and we haven't allocated enough space.
// We don't want to write past the end of what we allocated.
for i in 0 ..< count {
let byte = try container.decode(UInt8.self)
self[i] = byte
}
} else {
self.init()
}
while !container.isAtEnd {
var byte = try container.decode(UInt8.self)
self.append(&byte, count: 1)
}
}
public func encode(to encoder: Encoder) throws {
var container = encoder.unkeyedContainer()
try withUnsafeBytes { (buffer: UnsafeRawBufferPointer) in
try container.encode(contentsOf: buffer)
}
}
}
|
apache-2.0
|
155a731a4374bc01e1ea3a4c8140f4e3
| 44.34741 | 352 | 0.593181 | 5.127352 | false | false | false | false |
khizkhiz/swift
|
test/IRGen/Inputs/ObjectiveC.swift
|
2
|
1185
|
// This is an overlay Swift module.
@_exported import ObjectiveC
public struct ObjCBool : CustomStringConvertible {
#if os(OSX) || (os(iOS) && (arch(i386) || arch(arm)))
// On OS X and 32-bit iOS, Objective-C's BOOL type is a "signed char".
private var value: Int8
public init(_ value: Bool) {
self.value = value ? 1 : 0
}
/// \brief Allow use in a Boolean context.
public var boolValue: Bool {
return value != 0
}
#else
// Everywhere else it is C/C++'s "Bool"
private var value: Bool
public init(_ value: Bool) {
self.value = value
}
public var boolValue: Bool {
return value
}
#endif
public var description: String {
// Dispatch to Bool.
return self.boolValue.description
}
}
public struct Selector {
private var ptr : OpaquePointer
}
// Functions used to implicitly bridge ObjCBool types to Swift's Bool type.
public func _convertBoolToObjCBool(x: Bool) -> ObjCBool {
return ObjCBool(x)
}
public func _convertObjCBoolToBool(x: ObjCBool) -> Bool {
return x.boolValue
}
extension NSObject : Hashable {
public var hashValue: Int { return 0 }
}
public func ==(x: NSObject, y: NSObject) -> Bool { return x === y }
|
apache-2.0
|
dbe89da8ec0d5c498d8b117433ea264d
| 21.358491 | 75 | 0.669198 | 3.75 | false | false | false | false |
achimk/Swift-UIKit-Extensions
|
Extensions/UIResponder+Chain.swift
|
1
|
556
|
//
// UIResponder+Chain.swift
//
// Created by Joachim Kret on 24/09/15.
// Copyright © 2015 Perform. All rights reserved.
//
import UIKit
extension UIResponder {
func firstResponder(aClass: AnyClass) -> AnyObject? {
var responder: UIResponder? = self.nextResponder()
while responder != nil {
if responder?.isKindOfClass(aClass) == true {
return responder
} else {
responder = responder?.nextResponder()
}
}
return nil
}
}
|
mit
|
69a590a929cdc9fa1ff78804a3544d13
| 21.2 | 58 | 0.554955 | 4.826087 | false | false | false | false |
saurabytes/JSQCoreDataKit
|
Source/CoreDataStackFactory.swift
|
1
|
5860
|
//
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://www.jessesquires.com/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import CoreData
import Foundation
/**
An instance of `CoreDataStackFactory` is responsible for creating instances of `CoreDataStack`.
Because the adding of the persistent store to the persistent store coordinator during initialization
of a `CoreDataStack` can take an unknown amount of time, you should not perform this operation on the main queue.
See this [guide](https://developer.apple.com/library/prerelease/ios/documentation/Cocoa/Conceptual/CoreData/IntegratingCoreData.html#//apple_ref/doc/uid/TP40001075-CH9-SW1) for more details.
- warning: You should not create instances of `CoreDataStack` directly. Use a `CoreDataStackFactory` instead.
*/
public struct CoreDataStackFactory: CustomStringConvertible, Equatable {
// MARK: Properties
/// The model for the stack that the factory produces.
public let model: CoreDataModel
/**
A dictionary that specifies options for the store that the factory produces.
The default value is `DefaultStoreOptions`.
*/
public let options: PersistentStoreOptions?
// MARK: Initialization
/**
Constructs a new `CoreDataStackFactory` instance with the specified `model` and `options`.
- parameter model: The model describing the stack.
- parameter options: Options for the persistent store.
- returns: A new `CoreDataStackFactory` instance.
*/
public init(model: CoreDataModel, options: PersistentStoreOptions? = defaultStoreOptions) {
self.model = model
self.options = options
}
// MARK: Creating a stack
/**
Initializes a new `CoreDataStack` instance using the factory's `model` and `options`.
- warning: If a queue is provided, this operation is performed asynchronously on the specified queue,
and the completion closure is executed asynchronously on the main queue.
If `queue` is `nil`, then this method and the completion closure execute synchronously on the current queue.
- parameter queue: The queue on which to initialize the stack.
The default is a background queue with a "user initiated" quality of service class.
If passing `nil`, this method is executed synchronously on the queue from which the method was called.
- parameter completion: The closure to be called once initialization is complete.
If a queue is provided, this is called asynchronously on the main queue.
Otherwise, this is executed on the thread from which the method was originally called.
*/
public func createStack(onQueue queue: dispatch_queue_t? = dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0),
completion: (result: StackResult) -> Void) {
let isAsync = (queue != nil)
let creationClosure = {
let storeCoordinator: NSPersistentStoreCoordinator
do {
storeCoordinator = try self.createStoreCoordinator()
} catch {
if isAsync {
dispatch_async(dispatch_get_main_queue()) {
completion(result: .failure(error as NSError))
}
} else {
completion(result: .failure(error as NSError))
}
return
}
let backgroundContext = self.createContext(.PrivateQueueConcurrencyType, name: "background")
backgroundContext.persistentStoreCoordinator = storeCoordinator
let mainContext = self.createContext(.MainQueueConcurrencyType, name: "main")
mainContext.persistentStoreCoordinator = storeCoordinator
let stack = CoreDataStack(model: self.model,
mainContext: mainContext,
backgroundContext: backgroundContext,
storeCoordinator: storeCoordinator)
if isAsync {
dispatch_async(dispatch_get_main_queue()) {
completion(result: .success(stack))
}
} else {
completion(result: .success(stack))
}
}
if let queue = queue {
dispatch_async(queue, creationClosure)
} else {
creationClosure()
}
}
// MARK: Private
private func createStoreCoordinator() throws -> NSPersistentStoreCoordinator {
let storeCoordinator = NSPersistentStoreCoordinator(managedObjectModel: model.managedObjectModel)
try storeCoordinator.addPersistentStoreWithType(model.storeType.type,
configuration: nil,
URL: model.storeURL,
options: options)
return storeCoordinator
}
private func createContext(
concurrencyType: NSManagedObjectContextConcurrencyType,
name: String) -> NSManagedObjectContext {
let context = NSManagedObjectContext(concurrencyType: concurrencyType)
context.mergePolicy = NSMergePolicy(mergeType: .MergeByPropertyStoreTrumpMergePolicyType)
let contextName = "JSQCoreDataKit.CoreDataStack.context."
context.name = contextName + name
return context
}
// MARK: CustomStringConvertible
/// :nodoc:
public var description: String {
get {
return "<\(CoreDataStackFactory.self): model=\(model.name); options=\(options)>"
}
}
}
|
mit
|
b36d853028673ed6f12657f8f9d2fce3
| 35.849057 | 191 | 0.640041 | 5.522149 | false | false | false | false |
ObjSer/objser-swift
|
ObjSer/util/IO.swift
|
1
|
2005
|
//
// IO.swift
// ObjSer
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Greg Omelaenko
//
// 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.
//
public class OutputStream {
public init() { }
public private(set) var bytes = ByteArray()
func write(bytes: ByteArray) {
self.bytes.appendContentsOf(bytes)
}
func write(bytes: Byte...) {
self.bytes.appendContentsOf(bytes)
}
}
public class InputStream {
private let bytes: ByteArray
private var index: Int = 0
var hasBytesAvailable: Bool {
return index < bytes.count
}
public init(bytes: ByteArray) {
self.bytes = bytes
}
func readByte() -> Byte {
defer { index += 1 }
return bytes[index]
}
func readBytes(length length: Int) -> ArraySlice<Byte> {
let slice = bytes[index..<(index+length)]
index += length
return slice
}
}
|
mit
|
2ec5c480d18aa895ccb94a68f873d3f0
| 28.485294 | 82 | 0.664838 | 4.321121 | false | false | false | false |
tejasranade/KinveyHealth
|
SportShop/FeedItem.swift
|
1
|
1158
|
//
// FeedItem.swift
// SportShop
//
// Created by Tejas on 1/26/17.
// Copyright © 2017 Kinvey. All rights reserved.
//
import Foundation
import Kinvey
import ObjectMapper
class FeedItem : Entity {
dynamic var imageSource: String = ""
dynamic var name: String = ""
dynamic var desc: String = ""
// init (name: String, desc: String, imageSource: String) {
// self.name = name
// self.desc = desc
// self.imageSource = imageSource
// }
override class func collectionName() -> String {
//return the name of the backend collection corresponding to this entity
return "Feed"
}
//Map properties in your backend collection to the members of this entity
override func propertyMapping(_ map: Map) {
//This maps the "_id", "_kmd" and "_acl" properties
super.propertyMapping(map)
//Each property in your entity should be mapped using the following scheme:
//<member variable> <- ("<backend property>", map["<backend property>"])
name <- map["name"]
desc <- map["description"]
imageSource <- map["imageSource"]
}
}
|
apache-2.0
|
71619a436173630838af39a439e85bdb
| 27.925 | 83 | 0.621435 | 4.333333 | false | false | false | false |
koscida/Kos_AMAD_Spring2015
|
Spring_16/GRADE_projects/Project_2/Project2/Girl_Game/Girl_Game/GameLevel1Scene.swift
|
1
|
6859
|
//
// GameScene.swift
// Girl_Game
//
// Created by Brittany Kos on 4/6/16.
// Copyright (c) 2016 Kode Studios. All rights reserved.
//
import SpriteKit
class GameLevel1Scene: SKScene {
// frame things
var frameWidth: CGFloat = 0;
var frameHeight: CGFloat = 0;
var frameCenterWidth: CGFloat = 0;
var frameCenterHeight: CGFloat = 0;
let frameBorder: CGFloat = 20
// player
var player = CreateLevelSpritePlayer()
var movingPlayerUp = false;
var movingPlayerDown = false;
var playerBodyFile = ""
var playerArmorFile = ""
var playerWeaponFile = ""
// background
var backgroundCurrent1 = SKSpriteNode()
var backgroundCurrent2 = SKSpriteNode()
// screen options
override func didMoveToView(view: SKView) {
/* Setup your scene here */
// frame
frameWidth = CGRectGetWidth(frame)
frameCenterWidth = frameWidth / 2
frameHeight = CGRectGetHeight(frame)
frameCenterHeight = frameHeight / 2
// setup screen
//createSKShapeNodeRect
let arrowButtonWidth:CGFloat = 200;
let arrowButtonHeight:CGFloat = frameHeight / 2;
let arrowButtonX: CGFloat = 0
let arrowButtonDownY: CGFloat = 0
let arrowButtonUpY: CGFloat = arrowButtonDownY + arrowButtonHeight
let upButton = createSKShapeNodeRect(name: "upButton", rect: CGRect(x: arrowButtonX, y: arrowButtonUpY, width: arrowButtonWidth, height: arrowButtonHeight), fillColor: greyMediumColor)
upButton.strokeColor = greyDarkColor
upButton.lineWidth = 10
upButton.zPosition = 10
self.addChild(upButton)
let upButtonLabel = createSKLabelNodeAdj(name: "upButton", text: "Up", x: arrowButtonX + (arrowButtonWidth/2), y: arrowButtonUpY + (arrowButtonHeight/2), width: arrowButtonWidth, height: arrowButtonHeight, fontColor: UIColor.whiteColor())
upButtonLabel.zPosition = 11
self.addChild(upButtonLabel)
let downButton = createSKShapeNodeRect(name: "downButton", rect: CGRect(x: arrowButtonX, y: arrowButtonDownY, width: arrowButtonWidth, height: arrowButtonHeight), fillColor: greyMediumColor)
downButton.strokeColor = greyDarkColor
downButton.lineWidth = 10
downButton.zPosition = 10
self.addChild(downButton)
let downButtonLabel = createSKLabelNodeAdj(name: "downButton", text: "Down", x: arrowButtonX + (arrowButtonWidth/2), y: arrowButtonDownY + (arrowButtonHeight/2), width: arrowButtonWidth, height: arrowButtonHeight, fontColor: UIColor.whiteColor())
downButtonLabel.zPosition = 11
self.addChild(downButtonLabel)
// setup background
backgroundCurrent1.texture = SKTexture(imageNamed: "background_level1")
backgroundCurrent1.size = CGSize(width: frameWidth, height: frameHeight)
backgroundCurrent1.position = CGPoint(x: frameCenterWidth, y: frameCenterHeight)
backgroundCurrent1.name = "backgroundCurrent1"
backgroundCurrent1.zPosition = 1
self.addChild(backgroundCurrent1)
backgroundCurrent2.texture = SKTexture(imageNamed: "background_level1")
backgroundCurrent2.size = CGSize(width: frameWidth, height: frameHeight)
backgroundCurrent2.position = CGPoint(x: frameCenterWidth+frameWidth, y: frameCenterHeight)
backgroundCurrent2.name = "backgroundCurrent1"
backgroundCurrent2.zPosition = 1
self.addChild(backgroundCurrent2)
// setup player
let w = (frameHeight/5)
let h = w * (2400/1328)
print("playerBodyFile \(playerBodyFile) -- playerArmorFile \(playerArmorFile) -- playerWeaponFile \(playerWeaponFile)")
player = CreateLevelSpritePlayer(name: "player", bodyImageName: playerBodyFile, armorImageName: playerArmorFile, weaponImageName: playerWeaponFile, x: frameCenterWidth, y: frameCenterHeight, width: w, height: h, zPosition: 2)
self.addChild(player)
}
convenience init(size: CGSize, bodyFileName: String, armorFileName: String, weaponFileName: String) {
self.init(size: size)
playerBodyFile = bodyFileName
playerArmorFile = armorFileName
playerWeaponFile = weaponFileName
}
override init(size: CGSize) {
super.init(size: size)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
///////////////////////////////////////
// Scene loaders //
///////////////////////////////////////
////////////////////////////////////
// Game Logic //
////////////////////////////////////
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
/* Called when a touch begins */
for touch in touches {
let location = touch.locationInNode(self)
let touchedNode = self.nodeAtPoint(location)
if let name = touchedNode.name
{
// switching between options
if name == "upButton" {
//print("upButton")
movingPlayerUp = true;
} else if name == "downButton" {
//print("downButton")
movingPlayerDown = true;
}
}
}
}
override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
movingPlayerUp = false;
movingPlayerDown = false;
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
// update bacground
backgroundCurrent1.position.x -= 20
backgroundCurrent2.position.x -= 20
if(backgroundCurrent1.position.x <= (frameWidth/(-2))+19) {
backgroundCurrent1.position.x = frameWidth + (frameWidth/2)
}
if (backgroundCurrent2.position.x <= (frameWidth/(-2))+19) {
backgroundCurrent2.position.x = frameWidth + (frameWidth/2)
}
// update player sprite
if(movingPlayerUp) {
movePlayerUp();
}
if(movingPlayerDown) {
movePlayerDown();
}
}
func movePlayerUp() {
if player.position.y <= (frameHeight - (player.bodySprite.size.height/2)) {
player.position.y += 10
}
}
func movePlayerDown() {
if player.position.y >= (0 + (player.bodySprite.size.height/2)) {
player.position.y -= 10
}
}
}
|
gpl-3.0
|
d960b29c036d580dbc57613ab569f1ae
| 33.467337 | 254 | 0.593964 | 4.916846 | false | false | false | false |
NOTIFIT/notifit-ios-swift-sdk
|
Pod/Classes/NTFNetwork.swift
|
1
|
8069
|
//
// NTFNetwork.swift
// Pods
//
// Created by Tomas Sykora, jr. on 17/03/16.
//
//
import UIKit
import Foundation
class NTFNetwork: NSObject {
static let delegate = UIApplication.sharedApplication().delegate
class var api: NTFNetwork {
struct Static {
static let instance: NTFNetwork = NTFNetwork()
}
return Static.instance
}
func updateNotificationToken(notificationToken: NSData?){
addObservers()
var parameters = [
NTFConstants.value.applicationToken : NTFDefaults.getApplicationToken(),
NTFConstants.value.projectToken: NTFDefaults.getProjectToken()
] as Dictionary<String, AnyObject>
if notificationToken != nil {
let characterSet: NSCharacterSet = NSCharacterSet( charactersInString: "<>" )
let deviceTokenString: String = ( notificationToken!.description as NSString )
.stringByTrimmingCharactersInSet( characterSet )
.stringByReplacingOccurrencesOfString( " ", withString: "" ) as String
NTFLOG_I(deviceTokenString)
parameters.updateValue(deviceTokenString, forKey: "NotificationToken")
}
parameters += self.gatherDeviceInformation()
self.sendRequest(.PUT, url: NTFConstants.api.router.register, parameters: parameters)
}
func registerDeviceForProject(projectToken: String, forApplication applicationToken: String){
addObservers()
var parameters = [
"ProjectToken": projectToken,
"ApplicationToken": applicationToken,
"NotificationToken" : "NOTIFICATIONS_NOT_ALLOWED_NTF_FEKAL"
] as Dictionary<String, AnyObject>
parameters += self.gatherDeviceInformation()
if let _ = NTFDefaults.getCommunicationToken() {
self.sendRequest(.PUT, url: NTFConstants.api.router.register, parameters: parameters)
}else{
self.sendRequest(.POST, url: NTFConstants.api.router.register, parameters: parameters)
}
}
private func addObservers(){
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NTFNetwork.didFinishLaunchingWithOptions), name: UIApplicationDidFinishLaunchingNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NTFNetwork.applicationWillResignActive), name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NTFNetwork.applicationDidEnterBackground), name: UIApplicationDidEnterBackgroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NTFNetwork.applicationWillEnterForeground), name: UIApplicationWillEnterForegroundNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(NTFNetwork.applicationDidBecomeActive), name: UIApplicationDidBecomeActiveNotification, object: nil)
}
func sendNotificationToken(notificationToken: String, projectToken: String, applicationToken: String){
var parameters = [
"NotificationToken" : notificationToken,
"ProjectToken": projectToken,
"ApplicationToken": applicationToken
] as Dictionary<String, AnyObject>
parameters += self.gatherDeviceInformation()
if let _ = NTFDefaults.getCommunicationToken() {
self.sendRequest(.PUT, url: NTFConstants.api.router.register, parameters: parameters)
}else{
self.sendRequest(.POST, url: NTFConstants.api.router.register, parameters: parameters)
}
}
func sendKeyValue(value: String, key: String){
let parameters = [
"Value" : value,
"Key" : key
]
self.sendRequest(.POST, url: NTFConstants.api.router.keyValue, parameters: parameters)
}
func updateDeviceInformation(){
var parameters = [
NTFConstants.value.applicationToken : NTFDefaults.getApplicationToken(),
NTFConstants.value.projectToken: NTFDefaults.getProjectToken()
] as Dictionary<String, AnyObject>
parameters += self.gatherDeviceInformation()
debugPrint(parameters)
self.sendRequest(.PUT, url: NTFConstants.api.router.register, parameters: parameters)
}
func logApplicationState(state: NTFAppState){
let parameters = [
NTFConstants.api.applicationState : state.rawValue
]
sendRequest(.POST, url: NTFConstants.api.router.logState ,parameters: parameters)
}
private func gatherDeviceInformation() -> Dictionary<String,AnyObject> {
let device = UIDevice.currentDevice()
return [
"DeviceName":device.name,
"DeviceSystemName" : device.systemName,
"DeviceSystemVersion" : device.systemVersion,
"DeviceModel" : device.model,
"DeviceLocalizedModel" : device.localizedModel,
"DeviceIdentifierForVendor" : device.identifierForVendor?.UUIDString ?? "",
"DeviceTimeZone" : String(NSTimeZone.localTimeZone()),
"DevicePreferedLanguage" : NSLocale.preferredLanguages().first ?? "",
"DeviceCFBundleDisplayName" : (NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleDisplayName") ?? "") as! String,
"DeviceCFBundleShortVersionString" : (NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") ?? "") as! String,
"DeviceCFBundleVersion" : (NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleVersion") ?? "") as! String,
"DeviceBundleIdentifier" : NSBundle.mainBundle().bundleIdentifier ?? "",
"DeviceDifferenceToGMT" : NSTimeZone.localTimeZone().secondsFromGMT / 3600
]
}
private func sendRequest(method: NTFMethod, url: String, parameters: NSDictionary){
do {
debugPrint(parameters)
let jsonData = try NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted)
let url = NSURL(string: url)!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = method.rawValue
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
if (NTFDefaults.getCommunicationToken() != nil) {
request.setValue(NTFDefaults.getCommunicationToken()!, forHTTPHeaderField: NTFConstants.value.communicationToken)
}
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if let httpResponse = response as? NSHTTPURLResponse {
if let url = httpResponse.URL?.absoluteString {
NTFLOG_I("Status: \(httpResponse.statusCode) URL: \(url)")
if method == NTFMethod.PUT && httpResponse.statusCode != 200 {
NTFDefaults.deleteCommunicationToken()
self.registerDeviceForProject(NTFDefaults.getProjectToken(), forApplication: NTFDefaults.getApplicationToken())
}
if url == NTFConstants.api.router.register{
do {
if let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? [String:AnyObject] {
if let communicationToken = result["CommunicationToken"] as? String{
NTFDefaults.setCommunicationToken(communicationToken)
}
}
} catch (let error as NSError) {
NTFLOG_F(" \(error)")
}
}
}
}
if error != nil{
print("Error -> \(error)")
return
}
}
task.resume()
} catch {
print(error)
}
}
//MARK: - Application State
func didFinishLaunchingWithOptions(){
logApplicationState(.LAUNCH)
}
func applicationWillResignActive() {
logApplicationState(NTFAppState.RESIGNACTIVE)
}
func applicationDidEnterBackground() {
logApplicationState(NTFAppState.ENTERBACKGROUND)
}
func applicationWillEnterForeground(){
logApplicationState(NTFAppState.ENTERFOREGROUND)
}
func applicationDidBecomeActive() {
logApplicationState(NTFAppState.BECOMEACTIVE)
}
func applicationWillTerminate(){
logApplicationState(NTFAppState.TERMINATE)
}
}
// MARK: - Helpers
func += <KeyType, ValueType> (inout left: Dictionary<KeyType, ValueType>, right: Dictionary<KeyType, ValueType>) {
for (k, v) in right {
left.updateValue(v, forKey: k)
}
}
func NTFLOG_S(format: String = "")
{
debugPrint("NOTIFIT SUCCESS $ \(format)")
}
func NTFLOG_F(format: String = "")
{
debugPrint("NOTIFIT FAILURE $ \(format)")
}
func NTFLOG_I(format: String = "")
{
debugPrint("NOTIFIT INFO $ \(format)")
}
|
mit
|
915db80aecf09b8c3c59d08910e67f70
| 32.907563 | 185 | 0.74024 | 4.159278 | false | false | false | false |
aktowns/swen
|
Sources/Swen/Surface.swift
|
1
|
3297
|
//
// Surface.swift created on 27/12/15
// Swen project
//
// Copyright 2015 Ashley Towns <code@ashleytowns.id.au>
//
// 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 CSDL
public class Surface {
public typealias RawSurface = UnsafeMutablePointer<SDL_Surface>
let handle: RawSurface
public init(fromHandle handle: RawSurface) {
assert(handle != nil, "Surface.init(fromHandle:) given a null handle")
self.handle = handle
}
public convenience init(size: Size) {
let ptr = SDL_CreateRGBSurface(0, Int32(size.sizeX), Int32(size.sizeY),
32, Colour.red.hex, Colour.green.hex, Colour.blue.hex, 0x000000ff)
self.init(fromHandle: ptr)
}
deinit {
SDL_FreeSurface(self.handle)
}
public var format: UnsafeMutablePointer<SDL_PixelFormat> {
return self.handle.memory.format
}
public var size: Size {
return Size(sizeX: self.handle.memory.w, sizeY: self.handle.memory.h)
}
public var pitch: Int32 {
return self.handle.memory.pitch
}
public func blit(source src: Surface, sourceRect srcrect: Rect?) {
blit(source: src, sourceRect: srcrect, destRect: nil)
}
public func blit(source src: Surface, sourceRect srcrect: Rect?, destRect dstrect: Rect?) {
var srcRectptr = UnsafeMutablePointer<SDL_Rect>.alloc(1)
var dstRectptr = UnsafeMutablePointer<SDL_Rect>.alloc(1)
if let rect = srcrect {
let sdlRect = SDL_Rect.fromRect(rect)
srcRectptr.initialize(sdlRect)
} else {
srcRectptr = nil
}
if let rect = dstrect {
let sdlRect = SDL_Rect.fromRect(rect)
dstRectptr.initialize(sdlRect)
} else {
dstRectptr = nil
}
let res = SDL_UpperBlit(src.handle, srcRectptr, self.handle, dstRectptr)
assert(res == 0, "SDL_UpperBlit failed")
}
public func convert(format format: UnsafePointer<SDL_PixelFormat>) throws -> Surface {
let surf = SDL_ConvertSurface(self.handle, format, 0)
if surf == nil {
throw SDLError.ConvertSurfaceError(message: SDL.getErrorMessage())
}
return Surface(fromHandle: surf)
}
public func rotozoom(angle angle: Double, zoom: Double, smooth: Bool) -> Surface {
let ptr = rotozoomSurface(self.handle, angle, zoom, smooth ? 1 : 0)
return Surface(fromHandle: ptr)
}
public var colourKey: UInt32 {
get {
var key: UInt32 = 0
let res = SDL_GetColorKey(self.handle, &key)
assert(res == 0, "SDL_GetColorKey failed")
return key
}
}
public func enableColourKey(key: UInt32) {
let res = SDL_SetColorKey(self.handle, 1, key)
assert(res == 0, "SDL_SetColorKey failed")
}
public func disableColourKey(key: UInt32) {
let res = SDL_SetColorKey(self.handle, 0, key)
assert(res == 0, "SDL_SetColorKey")
}
}
|
apache-2.0
|
d94374a57a3fabaa7710fb2620d30efa
| 26.940678 | 93 | 0.679406 | 3.470526 | false | false | false | false |
huangboju/QMUI.swift
|
QMUI.swift/AppDelegate.swift
|
1
|
6298
|
//
// AppDelegate.swift
// QMUI.swift
//
// Created by 伯驹 黄 on 2017/1/17.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_: UIApplication, didFinishLaunchingWithOptions _: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// QD自定义的全局样式渲染
QDCommonUI.renderGlobalAppearances()
// 预加载 QQ 表情,避免第一次使用时卡顿
DispatchQueue.global().async {
QDUIHelper.qmuiEmotions()
}
// 界面
window = UIWindow(frame: UIScreen.main.bounds)
createTabBarController()
// 启动动画
startLaunchingAnimation()
return true
}
private func createTabBarController() {
let tabBarViewController = QDTabBarViewController()
// QMUIKit
let uikitViewController = QDUIKitViewController()
uikitViewController.hidesBottomBarWhenPushed = false
let uikitNavController = QDNavigationController(rootViewController: uikitViewController)
var image = UIImageMake("icon_tabbar_uikit")?.withRenderingMode(.alwaysOriginal)
var selectedImage = UIImageMake("icon_tabbar_uikit_selected")
uikitNavController.tabBarItem = QDUIHelper.tabBarItem(title: "QMUIKit", image: image, selectedImage: selectedImage, tag: 0)
// UIComponents
let componentViewController = QDComponentsViewController()
componentViewController.hidesBottomBarWhenPushed = false
let componentNavController = QDNavigationController(rootViewController: componentViewController)
image = UIImageMake("icon_tabbar_component")?.withRenderingMode(.alwaysOriginal)
selectedImage = UIImageMake("icon_tabbar_component_selected")
componentNavController.tabBarItem = QDUIHelper.tabBarItem(title: "Components", image: image, selectedImage: selectedImage, tag: 0)
// UIComponents
let labViewController = QDLabViewController()
labViewController.hidesBottomBarWhenPushed = false
let labNavController = QDNavigationController(rootViewController: labViewController)
image = UIImageMake("icon_tabbar_lab")?.withRenderingMode(.alwaysOriginal)
selectedImage = UIImageMake("icon_tabbar_lab_selected")
labNavController.tabBarItem = QDUIHelper.tabBarItem(title: "Lab", image: image, selectedImage: selectedImage, tag: 0)
// window root controller
tabBarViewController.viewControllers = [uikitNavController, componentNavController, labNavController]
window?.rootViewController = tabBarViewController
window?.makeKeyAndVisible()
}
private func startLaunchingAnimation() {
guard
let delegate = UIApplication.shared.delegate,
let window = delegate.window!,
let launchScreenView = Bundle.main.loadNibNamed("LaunchScreen", owner: self, options: nil)?.first as? UIView
else {
return
}
launchScreenView.frame = window.bounds
window.addSubview(launchScreenView)
let backgroundImageView = launchScreenView.subviews[0]
backgroundImageView.clipsToBounds = true
let logoImageView = launchScreenView.subviews[1]
let copyrightLabel = launchScreenView.subviews.last
let maskView = UIView(frame: launchScreenView.bounds)
maskView.backgroundColor = UIColorWhite
launchScreenView.insertSubview(maskView, belowSubview: backgroundImageView)
launchScreenView.layoutIfNeeded()
launchScreenView.constraints.forEach {
if $0.identifier == "bottomAlign" {
$0.isActive = false
NSLayoutConstraint.init(item: backgroundImageView, attribute: .bottom, relatedBy: .equal, toItem: launchScreenView, attribute: .top, multiplier: 1, constant: NavigationContentTop).isActive = true
return
}
}
UIView.animate(withDuration: 0.15, delay: 0.9, options: .curveOut, animations: {
launchScreenView.layoutIfNeeded()
logoImageView.alpha = 0
copyrightLabel?.alpha = 0
}, completion: nil)
UIView.animate(withDuration: 1.2, delay: 0.9, options: .curveEaseOut, animations: {
maskView.alpha = 0
backgroundImageView.alpha = 0
}) { (finished) in
launchScreenView.removeFromSuperview()
}
}
func applicationWillResignActive(_: 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 invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_: 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(_: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_: 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(_: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
mit
|
e6dd4154a410a4e5b99af5cac0405ab6
| 44.727941 | 285 | 0.686606 | 5.689844 | false | false | false | false |
Sufi-Al-Hussaini/Swift-CircleMenu
|
CircleMenu/CircleOverlayView.swift
|
1
|
3032
|
/**
The MIT License (MIT)
Copyright (c) 2016 Shoaib Ahmed / Sufi-Al-Hussaini
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.
*/
//
// CircleOverlayView.swift
// CircleMenu
//
// Created by Shoaib Ahmed on 11/26/16.
// Copyright © 2016 Shoaib Ahmed / Sufi-Al-Hussaini. All rights reserved.
//
import UIKit
class CircleOverlayView: UIView {
public var overlayThumb: CircleThumb!
public var circle: Circle?
public var controlPoint: CGPoint?
public var buttonCenter: CGPoint?
open override var center: CGPoint {
didSet {
self.circle?.center = buttonCenter!
}
}
required init?(with circle: Circle) {
if !circle.isRotate {
fatalError("init(with:) called for non-rotating circle")
}
let frame = circle.frame
super.init(frame: frame)
self.isOpaque = false
self.circle = circle
self.circle?.overlayView = self
var rect1 = CGRect(x: 0, y: 0, width: self.circle!.frame.height - (2*circle.ringWidth), height: self.circle!.frame.width - (2*circle.ringWidth))
rect1.origin.x = self.circle!.frame.size.width/2 - rect1.size.width/2
rect1.origin.y = 0
overlayThumb = CircleThumb(with: rect1.size.height/2, longRadius: self.circle!.frame.size.height/2, numberOfSegments: self.circle!.numberOfSegments)
overlayThumb?.isGradientFill = false
overlayThumb?.layer.position = CGPoint(x: frame.width/2, y: circle.ringWidth/2)
self.controlPoint = overlayThumb?.layer.position
self.addSubview(overlayThumb!)
overlayThumb?.arcColor = UIColor(red: 0.7, green: 0.7, blue: 0.7, alpha: 0.3)
self.buttonCenter = CGPoint(x: frame.midX, y: circle.frame.midY)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return false
}
}
|
mit
|
66e15cddef39f78f7e5971a85e7ad356
| 41.690141 | 461 | 0.684922 | 4.299291 | false | false | false | false |
fvaldez/score_point_ios
|
scorePoint/CustomButton.swift
|
1
|
2090
|
//
// CustomButton.swift
// BrainTeaser
//
// Created by Adriana Gonzalez on 3/31/16.
// Copyright © 2016 Adriana Gonzalez. All rights reserved.
//
import Foundation
import pop
@IBDesignable
class CustomButton: UIButton{
var willAnimate: Bool = false
@IBInspectable var cornerRadius: CGFloat = 3.0 {
didSet{
setupView()
}
}
@IBInspectable var fontColor: UIColor = UIColor.white{
didSet{
self.tintColor = fontColor
}
}
@IBInspectable var withAnimation: Bool = false {
didSet{
self.willAnimate = withAnimation
}
}
override func awakeFromNib() {
setupView()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setupView()
}
func setupView(){
self.layer.cornerRadius = cornerRadius
if(willAnimate == true){
self.addTarget(self, action: #selector(CustomButton.scaleAnimation), for: .touchUpInside)
self.addTarget(self, action: #selector(CustomButton.scaleDefault), for: .touchDragExit)
}
}
func scaleToSmall(){
let scaleAnim = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY)
scaleAnim?.toValue = NSValue(cgSize: CGSize(width: 0.95, height: 0.95))
self.layer.pop_add(scaleAnim, forKey: "layerScaleSmallAnimation")
}
func scaleAnimation(){
let scaleAnim = POPSpringAnimation(propertyNamed: kPOPLayerScaleXY)
scaleAnim?.velocity = NSValue(cgSize: CGSize(width: 3.0, height: 3.0))
scaleAnim?.toValue = NSValue(cgSize: CGSize(width: 1.0, height: 1.0))
scaleAnim?.springBounciness = 18
self.layer.pop_add(scaleAnim, forKey: "layerScaleSpringAnimation")
}
func scaleDefault() {
let scaleAnim = POPBasicAnimation(propertyNamed: kPOPLayerScaleXY)
scaleAnim?.toValue = NSValue(cgSize: CGSize(width: 1, height: 1))
self.layer.pop_add(scaleAnim, forKey: "layerScaleDefaultAnimation")
}
}
|
mit
|
9707dbbef02b70ee6b609f1f2f1c618b
| 27.22973 | 101 | 0.63236 | 4.758542 | false | false | false | false |
YPaul/compass
|
指南针/ViewController.swift
|
1
|
1708
|
//
// ViewController.swift
// 指南针
//
// Created by paul-y on 16/1/29.
// Copyright © 2016年 YX. All rights reserved.
//
import UIKit
import MapKit
class ViewController: UIViewController,CLLocationManagerDelegate {
@IBOutlet weak var dici: UIImageView!
@IBOutlet weak var dili: UIImageView!
/// 创建位置管理者
private let mgr = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
mgr.delegate = self
mgr.startUpdatingHeading()
}
/**
代理方法
*/
func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
/// 相对地理北极旋转角度
let dl_angle = newHeading.trueHeading * M_PI/180
/// 相对于地磁别急旋转角度
let dc_angle = newHeading.magneticHeading * M_PI/180
//根据方向角度,来旋转指南针图片
dici.transform = CGAffineTransformMakeRotation(-CGFloat(dc_angle))
dili.transform = CGAffineTransformMakeRotation(-CGFloat(dl_angle))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
设置不随屏幕旋转
*/
// override func shouldAutorotate() -> Bool {
// return false
// }
// override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
// return .Portrait
// }
// override func preferredInterfaceOrientationForPresentation() -> UIInterfaceOrientation {
// return .LandscapeLeft
// }
}
|
apache-2.0
|
5475da2c8f3c27e50305770e84a42a2b
| 27.375 | 94 | 0.646948 | 4.566092 | false | false | false | false |
austinzheng/swift
|
stdlib/public/core/Substring.swift
|
3
|
24258
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
extension String {
// FIXME(strings): at least temporarily remove it to see where it was applied
/// Creates a new string from the given substring.
///
/// - Parameter substring: A substring to convert to a standalone `String`
/// instance.
///
/// - Complexity: O(*n*), where *n* is the length of `substring`.
@inlinable
public init(_ substring: __shared Substring) {
self = String._fromSubstring(substring)
}
}
/// A slice of a string.
///
/// When you create a slice of a string, a `Substring` instance is the result.
/// Operating on substrings is fast and efficient because a substring shares
/// its storage with the original string. The `Substring` type presents the
/// same interface as `String`, so you can avoid or defer any copying of the
/// string's contents.
///
/// The following example creates a `greeting` string, and then finds the
/// substring of the first sentence:
///
/// let greeting = "Hi there! It's nice to meet you! 👋"
/// let endOfSentence = greeting.firstIndex(of: "!")!
/// let firstSentence = greeting[...endOfSentence]
/// // firstSentence == "Hi there!"
///
/// You can perform many string operations on a substring. Here, we find the
/// length of the first sentence and create an uppercase version.
///
/// print("'\(firstSentence)' is \(firstSentence.count) characters long.")
/// // Prints "'Hi there!' is 9 characters long."
///
/// let shoutingSentence = firstSentence.uppercased()
/// // shoutingSentence == "HI THERE!"
///
/// Converting a Substring to a String
/// ==================================
///
/// This example defines a `rawData` string with some unstructured data, and
/// then uses the string's `prefix(while:)` method to create a substring of
/// the numeric prefix:
///
/// let rawInput = "126 a.b 22219 zzzzzz"
/// let numericPrefix = rawInput.prefix(while: { "0"..."9" ~= $0 })
/// // numericPrefix is the substring "126"
///
/// When you need to store a substring or pass it to a function that requires a
/// `String` instance, you can convert it to a `String` by using the
/// `String(_:)` initializer. Calling this initializer copies the contents of
/// the substring to a new string.
///
/// func parseAndAddOne(_ s: String) -> Int {
/// return Int(s, radix: 10)! + 1
/// }
/// _ = parseAndAddOne(numericPrefix)
/// // error: cannot convert value...
/// let incrementedPrefix = parseAndAddOne(String(numericPrefix))
/// // incrementedPrefix == 127
///
/// Alternatively, you can convert the function that takes a `String` to one
/// that is generic over the `StringProtocol` protocol. The following code
/// declares a generic version of the `parseAndAddOne(_:)` function:
///
/// func genericParseAndAddOne<S: StringProtocol>(_ s: S) -> Int {
/// return Int(s, radix: 10)! + 1
/// }
/// let genericallyIncremented = genericParseAndAddOne(numericPrefix)
/// // genericallyIncremented == 127
///
/// You can call this generic function with an instance of either `String` or
/// `Substring`.
///
/// - Important: Don't store substrings longer than you need them to perform a
/// specific operation. A substring holds a reference to the entire storage
/// of the string it comes from, not just to the portion it presents, even
/// when there is no other reference to the original string. Storing
/// substrings may, therefore, prolong the lifetime of string data that is
/// no longer otherwise accessible, which can appear to be memory leakage.
@_fixed_layout
public struct Substring {
@usableFromInline
internal var _slice: Slice<String>
@inlinable @inline(__always)
internal init(_ slice: Slice<String>) {
self._slice = slice
_invariantCheck()
}
@inline(__always)
internal init(_ slice: _StringGutsSlice) {
self.init(String(slice._guts)[slice.range])
}
/// Creates an empty substring.
@inlinable @inline(__always)
public init() {
self.init(Slice())
}
}
extension Substring {
@inlinable
internal var _wholeGuts: _StringGuts {
@inline(__always) get { return _slice.base._guts }
}
@inlinable
internal var _wholeString: String {
@inline(__always) get { return String(self._wholeGuts) }
}
@inlinable
internal var _offsetRange: Range<Int> {
@inline(__always) get {
let start = _slice.startIndex
let end = _slice.endIndex
_internalInvariant(start.transcodedOffset == 0 && end.transcodedOffset == 0)
return Range(uncheckedBounds: (start.encodedOffset, end.encodedOffset))
}
}
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
self._wholeString._invariantCheck()
}
#endif // INTERNAL_CHECKS_ENABLED
}
extension Substring: StringProtocol {
public typealias Index = String.Index
public typealias SubSequence = Substring
@inlinable
public var startIndex: Index {
@inline(__always) get { return _slice.startIndex }
}
@inlinable
public var endIndex: Index {
@inline(__always) get { return _slice.endIndex }
}
@inlinable @inline(__always)
public func index(after i: Index) -> Index {
_precondition(i < endIndex, "Cannot increment beyond endIndex")
_precondition(i >= startIndex, "Cannot increment an invalid index")
return _slice.index(after: i)
}
@inlinable @inline(__always)
public func index(before i: Index) -> Index {
_precondition(i <= endIndex, "Cannot decrement an invalid index")
_precondition(i > startIndex, "Cannot decrement beyond startIndex")
return _slice.index(before: i)
}
@inlinable @inline(__always)
public func index(_ i: Index, offsetBy n: Int) -> Index {
let result = _slice.index(i, offsetBy: n)
_precondition(
(_slice._startIndex ... _slice.endIndex).contains(result),
"Operation results in an invalid index")
return result
}
@inlinable @inline(__always)
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
let result = _slice.index(i, offsetBy: n, limitedBy: limit)
_precondition(result.map {
(_slice._startIndex ... _slice.endIndex).contains($0)
} ?? true,
"Operation results in an invalid index")
return result
}
@inlinable @inline(__always)
public func distance(from start: Index, to end: Index) -> Int {
return _slice.distance(from: start, to: end)
}
public subscript(i: Index) -> Character {
return _slice[i]
}
public mutating func replaceSubrange<C>(
_ bounds: Range<Index>,
with newElements: C
) where C : Collection, C.Iterator.Element == Iterator.Element {
_slice.replaceSubrange(bounds, with: newElements)
}
public mutating func replaceSubrange(
_ bounds: Range<Index>, with newElements: Substring
) {
replaceSubrange(bounds, with: newElements._slice)
}
/// Creates a string from the given Unicode code units in the specified
/// encoding.
///
/// - Parameters:
/// - codeUnits: A collection of code units encoded in the encoding
/// specified in `sourceEncoding`.
/// - sourceEncoding: The encoding in which `codeUnits` should be
/// interpreted.
@inlinable // specialization
public init<C: Collection, Encoding: _UnicodeEncoding>(
decoding codeUnits: C, as sourceEncoding: Encoding.Type
) where C.Iterator.Element == Encoding.CodeUnit {
self.init(String(decoding: codeUnits, as: sourceEncoding))
}
/// Creates a string from the null-terminated, UTF-8 encoded sequence of
/// bytes at the given pointer.
///
/// - Parameter nullTerminatedUTF8: A pointer to a sequence of contiguous,
/// UTF-8 encoded bytes ending just before the first zero byte.
public init(cString nullTerminatedUTF8: UnsafePointer<CChar>) {
self.init(String(cString: nullTerminatedUTF8))
}
/// Creates a string from the null-terminated sequence of bytes at the given
/// pointer.
///
/// - Parameters:
/// - nullTerminatedCodeUnits: A pointer to a sequence of contiguous code
/// units in the encoding specified in `sourceEncoding`, ending just
/// before the first zero code unit.
/// - sourceEncoding: The encoding in which the code units should be
/// interpreted.
@inlinable // specialization
public init<Encoding: _UnicodeEncoding>(
decodingCString nullTerminatedCodeUnits: UnsafePointer<Encoding.CodeUnit>,
as sourceEncoding: Encoding.Type
) {
self.init(
String(decodingCString: nullTerminatedCodeUnits, as: sourceEncoding))
}
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of UTF-8 code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(_:)`. Do not store or return the pointer for
/// later use.
///
/// - Parameter body: A closure with a pointer parameter that points to a
/// null-terminated sequence of UTF-8 code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(_:)` method. The pointer argument is valid only for the
/// duration of the method's execution.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // specialization
public func withCString<Result>(
_ body: (UnsafePointer<CChar>) throws -> Result) rethrows -> Result {
// TODO(String performance): Detect when we cover the rest of a nul-
// terminated String, and thus can avoid a copy.
return try String(self).withCString(body)
}
/// Calls the given closure with a pointer to the contents of the string,
/// represented as a null-terminated sequence of code units.
///
/// The pointer passed as an argument to `body` is valid only during the
/// execution of `withCString(encodedAs:_:)`. Do not store or return the
/// pointer for later use.
///
/// - Parameters:
/// - body: A closure with a pointer parameter that points to a
/// null-terminated sequence of code units. If `body` has a return
/// value, that value is also used as the return value for the
/// `withCString(encodedAs:_:)` method. The pointer argument is valid
/// only for the duration of the method's execution.
/// - targetEncoding: The encoding in which the code units should be
/// interpreted.
/// - Returns: The return value, if any, of the `body` closure parameter.
@inlinable // specialization
public func withCString<Result, TargetEncoding: _UnicodeEncoding>(
encodedAs targetEncoding: TargetEncoding.Type,
_ body: (UnsafePointer<TargetEncoding.CodeUnit>) throws -> Result
) rethrows -> Result {
// TODO(String performance): Detect when we cover the rest of a nul-
// terminated String, and thus can avoid a copy.
return try String(self).withCString(encodedAs: targetEncoding, body)
}
}
extension Substring : CustomReflectable {
public var customMirror: Mirror { return String(self).customMirror }
}
extension Substring : CustomStringConvertible {
@inlinable
public var description: String {
@inline(__always) get { return String(self) }
}
}
extension Substring : CustomDebugStringConvertible {
public var debugDescription: String { return String(self).debugDescription }
}
extension Substring : LosslessStringConvertible {
@inlinable
public init(_ content: String) {
self = content[...]
}
}
extension Substring {
@_fixed_layout
public struct UTF8View {
@usableFromInline
internal var _slice: Slice<String.UTF8View>
}
}
extension Substring.UTF8View : BidirectionalCollection {
public typealias Index = String.UTF8View.Index
public typealias Indices = String.UTF8View.Indices
public typealias Element = String.UTF8View.Element
public typealias SubSequence = Substring.UTF8View
/// Creates an instance that slices `base` at `_bounds`.
@inlinable
internal init(_ base: String.UTF8View, _bounds: Range<Index>) {
_slice = Slice(
base: String(base._guts).utf8,
bounds: _bounds)
}
//
// Plumb slice operations through
//
@inlinable
public var startIndex: Index { return _slice.startIndex }
@inlinable
public var endIndex: Index { return _slice.endIndex }
@inlinable
public subscript(index: Index) -> Element { return _slice[index] }
@inlinable
public var indices: Indices { return _slice.indices }
@inlinable
public func index(after i: Index) -> Index { return _slice.index(after: i) }
@inlinable
public func formIndex(after i: inout Index) {
_slice.formIndex(after: &i)
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return _slice.index(i, offsetBy: n)
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return _slice.index(i, offsetBy: n, limitedBy: limit)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _slice.distance(from: start, to: end)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_slice._failEarlyRangeCheck(index, bounds: bounds)
}
@inlinable
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_slice._failEarlyRangeCheck(range, bounds: bounds)
}
public func index(before i: Index) -> Index { return _slice.index(before: i) }
public func formIndex(before i: inout Index) {
_slice.formIndex(before: &i)
}
public subscript(r: Range<Index>) -> Substring.UTF8View {
// FIXME(strings): tests.
_precondition(r.lowerBound >= startIndex && r.upperBound <= endIndex,
"UTF8View index range out of bounds")
return Substring.UTF8View(_slice.base, _bounds: r)
}
}
extension Substring {
@inlinable
public var utf8: UTF8View {
get {
return _wholeString.utf8[startIndex..<endIndex]
}
set {
self = Substring(newValue)
}
}
/// Creates a Substring having the given content.
///
/// - Complexity: O(1)
public init(_ content: UTF8View) {
self = String(
content._slice.base._guts
)[content.startIndex..<content.endIndex]
}
}
extension String {
/// Creates a String having the given content.
///
/// If `codeUnits` is an ill-formed code unit sequence, the result is `nil`.
///
/// - Complexity: O(N), where N is the length of the resulting `String`'s
/// UTF-16.
public init?(_ codeUnits: Substring.UTF8View) {
let guts = codeUnits._slice.base._guts
guard guts.isOnUnicodeScalarBoundary(codeUnits._slice.startIndex),
guts.isOnUnicodeScalarBoundary(codeUnits._slice.endIndex) else {
return nil
}
self = String(Substring(codeUnits))
}
}
extension Substring {
@_fixed_layout
public struct UTF16View {
@usableFromInline
internal var _slice: Slice<String.UTF16View>
}
}
extension Substring.UTF16View : BidirectionalCollection {
public typealias Index = String.UTF16View.Index
public typealias Indices = String.UTF16View.Indices
public typealias Element = String.UTF16View.Element
public typealias SubSequence = Substring.UTF16View
/// Creates an instance that slices `base` at `_bounds`.
@inlinable
internal init(_ base: String.UTF16View, _bounds: Range<Index>) {
_slice = Slice(
base: String(base._guts).utf16,
bounds: _bounds)
}
//
// Plumb slice operations through
//
@inlinable
public var startIndex: Index { return _slice.startIndex }
@inlinable
public var endIndex: Index { return _slice.endIndex }
@inlinable
public subscript(index: Index) -> Element { return _slice[index] }
@inlinable
public var indices: Indices { return _slice.indices }
@inlinable
public func index(after i: Index) -> Index { return _slice.index(after: i) }
@inlinable
public func formIndex(after i: inout Index) {
_slice.formIndex(after: &i)
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return _slice.index(i, offsetBy: n)
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return _slice.index(i, offsetBy: n, limitedBy: limit)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _slice.distance(from: start, to: end)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_slice._failEarlyRangeCheck(index, bounds: bounds)
}
@inlinable
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_slice._failEarlyRangeCheck(range, bounds: bounds)
}
@inlinable
public func index(before i: Index) -> Index { return _slice.index(before: i) }
@inlinable
public func formIndex(before i: inout Index) {
_slice.formIndex(before: &i)
}
@inlinable
public subscript(r: Range<Index>) -> Substring.UTF16View {
return Substring.UTF16View(_slice.base, _bounds: r)
}
}
extension Substring {
@inlinable
public var utf16: UTF16View {
get {
return _wholeString.utf16[startIndex..<endIndex]
}
set {
self = Substring(newValue)
}
}
/// Creates a Substring having the given content.
///
/// - Complexity: O(1)
public init(_ content: UTF16View) {
self = String(
content._slice.base._guts
)[content.startIndex..<content.endIndex]
}
}
extension String {
/// Creates a String having the given content.
///
/// If `codeUnits` is an ill-formed code unit sequence, the result is `nil`.
///
/// - Complexity: O(N), where N is the length of the resulting `String`'s
/// UTF-16.
public init?(_ codeUnits: Substring.UTF16View) {
let guts = codeUnits._slice.base._guts
guard guts.isOnUnicodeScalarBoundary(codeUnits._slice.startIndex),
guts.isOnUnicodeScalarBoundary(codeUnits._slice.endIndex) else {
return nil
}
self = String(Substring(codeUnits))
}
}
extension Substring {
@_fixed_layout
public struct UnicodeScalarView {
@usableFromInline
internal var _slice: Slice<String.UnicodeScalarView>
}
}
extension Substring.UnicodeScalarView : BidirectionalCollection {
public typealias Index = String.UnicodeScalarView.Index
public typealias Indices = String.UnicodeScalarView.Indices
public typealias Element = String.UnicodeScalarView.Element
public typealias SubSequence = Substring.UnicodeScalarView
/// Creates an instance that slices `base` at `_bounds`.
@inlinable
internal init(_ base: String.UnicodeScalarView, _bounds: Range<Index>) {
_slice = Slice(
base: String(base._guts).unicodeScalars,
bounds: _bounds)
}
//
// Plumb slice operations through
//
@inlinable
public var startIndex: Index { return _slice.startIndex }
@inlinable
public var endIndex: Index { return _slice.endIndex }
@inlinable
public subscript(index: Index) -> Element { return _slice[index] }
@inlinable
public var indices: Indices { return _slice.indices }
@inlinable
public func index(after i: Index) -> Index { return _slice.index(after: i) }
@inlinable
public func formIndex(after i: inout Index) {
_slice.formIndex(after: &i)
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
return _slice.index(i, offsetBy: n)
}
@inlinable
public func index(
_ i: Index, offsetBy n: Int, limitedBy limit: Index
) -> Index? {
return _slice.index(i, offsetBy: n, limitedBy: limit)
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return _slice.distance(from: start, to: end)
}
@inlinable
public func _failEarlyRangeCheck(_ index: Index, bounds: Range<Index>) {
_slice._failEarlyRangeCheck(index, bounds: bounds)
}
@inlinable
public func _failEarlyRangeCheck(
_ range: Range<Index>, bounds: Range<Index>
) {
_slice._failEarlyRangeCheck(range, bounds: bounds)
}
@inlinable
public func index(before i: Index) -> Index { return _slice.index(before: i) }
@inlinable
public func formIndex(before i: inout Index) {
_slice.formIndex(before: &i)
}
@inlinable
public subscript(r: Range<Index>) -> Substring.UnicodeScalarView {
return Substring.UnicodeScalarView(_slice.base, _bounds: r)
}
}
extension Substring {
@inlinable
public var unicodeScalars: UnicodeScalarView {
get {
return _wholeString.unicodeScalars[startIndex..<endIndex]
}
set {
self = Substring(newValue)
}
}
/// Creates a Substring having the given content.
///
/// - Complexity: O(1)
public init(_ content: UnicodeScalarView) {
self = String(
content._slice.base._guts
)[content.startIndex..<content.endIndex]
}
}
extension String {
/// Creates a String having the given content.
///
/// - Complexity: O(N), where N is the length of the resulting `String`'s
/// UTF-16.
public init(_ content: Substring.UnicodeScalarView) {
self = String(Substring(content))
}
}
// FIXME: The other String views should be RangeReplaceable too.
extension Substring.UnicodeScalarView : RangeReplaceableCollection {
@inlinable
public init() { _slice = Slice.init() }
public mutating func replaceSubrange<C : Collection>(
_ target: Range<Index>, with replacement: C
) where C.Element == Element {
_slice.replaceSubrange(target, with: replacement)
}
}
extension Substring : RangeReplaceableCollection {
@_specialize(where S == String)
@_specialize(where S == Substring)
@_specialize(where S == Array<Character>)
public init<S : Sequence>(_ elements: S)
where S.Element == Character {
if let str = elements as? String {
self = str[...]
return
}
if let subStr = elements as? Substring {
self = subStr
return
}
self = String(elements)[...]
}
@inlinable // specialize
public mutating func append<S : Sequence>(contentsOf elements: S)
where S.Element == Character {
var string = String(self)
self = Substring() // Keep unique storage if possible
string.append(contentsOf: elements)
self = Substring(string)
}
}
extension Substring {
public func lowercased() -> String {
return String(self).lowercased()
}
public func uppercased() -> String {
return String(self).uppercased()
}
public func filter(
_ isIncluded: (Element) throws -> Bool
) rethrows -> String {
return try String(self.lazy.filter(isIncluded))
}
}
extension Substring : TextOutputStream {
public mutating func write(_ other: String) {
append(contentsOf: other)
}
}
extension Substring : TextOutputStreamable {
@inlinable // specializable
public func write<Target : TextOutputStream>(to target: inout Target) {
target.write(String(self))
}
}
extension Substring : ExpressibleByUnicodeScalarLiteral {
@inlinable
public init(unicodeScalarLiteral value: String) {
self.init(value)
}
}
extension Substring : ExpressibleByExtendedGraphemeClusterLiteral {
@inlinable
public init(extendedGraphemeClusterLiteral value: String) {
self.init(value)
}
}
extension Substring : ExpressibleByStringLiteral {
@inlinable
public init(stringLiteral value: String) {
self.init(value)
}
}
// String/Substring Slicing
extension String {
@inlinable
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> Substring {
_boundsCheck(r)
return Substring(Slice(base: self, bounds: r))
}
}
extension Substring {
@inlinable
@available(swift, introduced: 4)
public subscript(r: Range<Index>) -> Substring {
return Substring(_slice[r])
}
}
|
apache-2.0
|
74a43263d354b6e8134be2a137b4b134
| 29.018564 | 82 | 0.675861 | 4.176136 | false | false | false | false |
kidaa/codecombat-ios
|
CodeCombat/WebManager.swift
|
2
|
12097
|
//
// WebManager.swift
// iPadClient
//
// Created by Michael Schmatz on 7/26/14.
// Copyright (c) 2014 CodeCombat. All rights reserved.
//
import UIKit
import WebKit
class WebManager: NSObject, WKScriptMessageHandler, WKNavigationDelegate {
var webViewConfiguration: WKWebViewConfiguration!
var urlSesssionConfiguration: NSURLSessionConfiguration?
let allowedRoutePrefixes = ["http://localhost:3000", "https://codecombat.com"]
var operationQueue: NSOperationQueue?
var webView: WKWebView? // Assign this if we create one, so that we can evaluate JS in its context.
var lastJSEvaluated: String?
var scriptMessageNotificationCenter: NSNotificationCenter!
var activeSubscriptions = [String: Int]()
var activeObservers = [NSObject : [String]]()
var hostReachibility:Reachability!
var authCookieIsFresh:Bool = false
var webKitCheckupTimer: NSTimer?
var webKitCheckupsMissed: Int = -1
var currentFragment: String?
var afterLoginFragment: String?
class var sharedInstance:WebManager {
return WebManagerSharedInstance
}
func checkReachibility() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("reachibilityChanged:"), name: kReachabilityChangedNotification, object: nil)
hostReachibility = Reachability(hostName: "codecombat.com")
hostReachibility.startNotifier()
}
func reachibilityChanged(note:NSNotification) {
if hostReachibility.currentReachabilityStatus().rawValue == NotReachable.rawValue {
print("Host unreachable")
NSNotificationCenter.defaultCenter().postNotificationName("websiteNotReachable", object: nil)
} else {
print("Host reachable!")
NSNotificationCenter.defaultCenter().postNotificationName("websiteReachable", object: nil)
}
}
override init() {
super.init()
operationQueue = NSOperationQueue()
scriptMessageNotificationCenter = NSNotificationCenter()
instantiateWebView()
subscribe(self, channel: "application:error", selector: "onJSError:")
subscribe(self, channel: "router:navigated", selector: Selector("onNavigated:"))
webKitCheckupTimer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("checkWebKit"), userInfo: nil, repeats: true)
}
private func instantiateWebView() {
let WebViewFrame = CGRectMake(0, 0, 1024, 768) // Full-size
webViewConfiguration = WKWebViewConfiguration()
addScriptMessageHandlers()
webView = WKWebView(frame: WebViewFrame, configuration: webViewConfiguration)
webView!.navigationDelegate = self
// if let email = User.currentUser?.email, password = User.currentUser?.password {
// logIn(email: email, password: password)
// }
}
func removeAllUserScripts() {
webViewConfiguration!.userContentController.removeAllUserScripts()
}
func webView(webView: WKWebView, didCommitNavigation navigation: WKNavigation!) {
print("Comitted navigation to \(webView.URL)")
if !routeURLHasAllowedPrefix(webView.URL!.absoluteString) {
webView.stopLoading()
webView.loadRequest(NSURLRequest(URL: NSURL(string: "/play", relativeToURL: rootURL)!))
} else {
//Inject the no-zoom javascript
let noZoomJS = "var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);"
webView.evaluateJavaScript(noZoomJS, completionHandler: nil)
print("webView didCommitNavigation")
}
currentFragment = self.webView!.URL!.path!
}
func routeURLHasAllowedPrefix(route:String) -> Bool {
for allowedPrefix in allowedRoutePrefixes {
if route.hasPrefix(allowedPrefix) {
return true
}
}
return false
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
NSNotificationCenter.defaultCenter().postNotificationName("webViewDidFinishNavigation", object: nil)
print("webView didFinishNavigation")
for (channel, count) in activeSubscriptions {
if count > 0 {
print("Reregistering \(channel)")
registerSubscription(channel)
}
}
if afterLoginFragment != nil {
print("Now that we have logged in, we are navigating to \(afterLoginFragment!)")
publish("router:navigate", event: ["route": afterLoginFragment!])
afterLoginFragment = nil
}
}
//requires that User.email and User.password are set
func createAnonymousUser() {
guard let username = User.currentUser?.username, password = User.currentUser?.password else { return }
//should include something
let creationScript = "function makeAnonymousUser() { me.set('iosIdentifierForVendor','\(username)'); me.set('password','\(password)'); me.save();} if (!me.get('iosIdentifierForVendor') && me.get('anonymous')) setTimeout(makeAnonymousUser,1);"
print("Injecting script \(creationScript)")
let userScript = WKUserScript(source: creationScript, injectionTime: .AtDocumentEnd, forMainFrameOnly: true)
webViewConfiguration!.userContentController.addUserScript(userScript)
let requestURL = NSURL(string: "/play", relativeToURL: rootURL)
let request = NSMutableURLRequest(URL: requestURL!)
webView!.loadRequest(request)
}
func subscribe(observer: AnyObject, channel: String, selector: Selector) {
scriptMessageNotificationCenter.addObserver(observer, selector: selector, name: channel, object: self)
if activeSubscriptions[channel] == nil {
activeSubscriptions[channel] = 0
}
activeSubscriptions[channel] = activeSubscriptions[channel]! + 1
if activeObservers[observer as! NSObject] == nil {
activeObservers[observer as! NSObject] = []
}
activeObservers[observer as! NSObject]!.append(channel)
if activeSubscriptions[channel] == 1 {
registerSubscription(channel)
}
//println("Subscribed \(observer) to \(channel) so now have activeSubscriptions \(activeSubscriptions) activeObservers \(activeObservers)")
}
private func registerSubscription(channel: String) {
evaluateJavaScript([
"window.addIPadSubscriptionIfReady = function(channel) {",
" if (window.addIPadSubscription) {",
" window.addIPadSubscription(channel);",
" console.log('Totally subscribed to', channel);",
" }",
" else {",
" console.log('Could not add iPad subscription', channel, 'yet.')",
" setTimeout(function() { window.addIPadSubcriptionIfReady(channel); }, 500);",
" }",
"}",
"window.addIPadSubscriptionIfReady('\(channel)');"
].joinWithSeparator("\n"), completionHandler: nil)
}
func unsubscribe(observer: AnyObject) {
scriptMessageNotificationCenter.removeObserver(observer)
if let channels = activeObservers[observer as! NSObject] {
for channel in channels {
activeSubscriptions[channel] = activeSubscriptions[channel]! - 1
if activeSubscriptions[channel] == 0 {
evaluateJavaScript("if(window.removeIPadSubscription) window.removeIPadSubscription('\(channel)');", completionHandler: nil)
}
}
activeObservers.removeValueForKey(observer as! NSObject)
//println("Unsubscribed \(observer) from \(channels) so now have activeSubscriptions \(activeSubscriptions) activeObservers \(activeObservers)")
}
}
func publish(channel: String, event: Dictionary<String, AnyObject>) {
let serializedEvent = serializeData(event)
evaluateJavaScript("Backbone.Mediator.publish('\(channel)', \(serializedEvent))", completionHandler: onJSEvaluated)
}
func evaluateJavaScript(js: String, completionHandler: ((AnyObject?, NSError?) -> Void)?) {
let handler = completionHandler == nil ? onJSEvaluated : completionHandler! // There's got to be a more Swifty way of doing this.
lastJSEvaluated = js
//println(" evaluating JS: \(js)")
webView?.evaluateJavaScript(js, completionHandler: handler) // This isn't documented, so is it being added or removed or what?
}
func onJSEvaluated(response: AnyObject?, error: NSError?) {
if error != nil {
print("There was an error evaluating JS: \(error), response: \(response)")
print("JS was \(lastJSEvaluated!)")
} else if response != nil {
//println("Got response from evaluating JS: \(response)")
}
}
func onJSError(note: NSNotification) {
if let event = note.userInfo {
let message = event["message"]! as! String
print("💔💔💔 Unhandled JS error in application: \(message)")
}
}
func onNavigated(note: NSNotification) {
if let event = note.userInfo {
let route = event["route"]! as! String
currentFragment = route
}
}
private func serializeData(data: NSDictionary?) -> String {
var serialized: NSData?
if data != nil {
do {
serialized = try NSJSONSerialization.dataWithJSONObject(data!, options: NSJSONWritingOptions(rawValue: 0))
} catch {
serialized = nil
}
} else {
let EmptyObjectString = NSString(string: "{}")
serialized = EmptyObjectString.dataUsingEncoding(NSUTF8StringEncoding)
}
return NSString(data: serialized!, encoding: NSUTF8StringEncoding)! as String
}
func userContentController(userContentController: WKUserContentController, didReceiveScriptMessage message: WKScriptMessage) {
if message.name == "backboneEventHandler" {
// Turn Backbone events into NSNotifications
let body = (message.body as! NSDictionary) as Dictionary // You... It... So help me...
let channel = body["channel"] as! String
let event = (body["event"] as! NSDictionary) as Dictionary
//println("got backbone event: \(channel)")
scriptMessageNotificationCenter.postNotificationName(channel, object: self, userInfo: event)
} else if message.name == "consoleLogHandler" {
let body = (message.body as! NSDictionary) as Dictionary
let level = body["level"] as! String
let arguments = body["arguments"] as! NSArray
let message = arguments.componentsJoinedByString(" ")
print("\(colorEmoji[level]!) \(level): \(message)")
}
else {
print("got message: \(message.name): \(message.body)")
scriptMessageNotificationCenter.postNotificationName(message.name, object: self, userInfo: message.body as? [NSObject:AnyObject])
}
}
func addScriptMessageHandlers() {
let contentController = webViewConfiguration!.userContentController
contentController.addScriptMessageHandler(self, name: "backboneEventHandler")
contentController.addScriptMessageHandler(self, name: "consoleLogHandler")
}
func onWebKitCheckupAnswered(response: AnyObject?, error: NSError?) {
if response != nil {
webKitCheckupsMissed = -1
//println("WebView just checked in with response \(response), error \(error?)")
}
else {
print("WebKit missed a checkup. It's either slow to respond, or has crashed. (Probably just slow to respond.)")
webKitCheckupsMissed = 100
}
}
func checkWebKit() {
//println("webView is \(webView?); asking it to check in")
if webKitCheckupsMissed > 60 {
print("-----------------Oh snap, it crashed!---------------------")
webKitCheckupsMissed = -1
reloadWebView()
}
++webKitCheckupsMissed;
evaluateJavaScript("2 + 2;", completionHandler: onWebKitCheckupAnswered)
}
func reloadWebView() {
let oldSuperView = webView!.superview
if oldSuperView != nil {
webView!.removeFromSuperview()
}
afterLoginFragment = currentFragment
webView = nil
instantiateWebView()
if oldSuperView != nil {
oldSuperView?.addSubview(webView!)
}
print("WebManager reloaded webview: \(webView!)")
NSNotificationCenter.defaultCenter().postNotificationName("webViewReloadedFromCrash", object: self)
}
}
private let WebManagerSharedInstance = WebManager()
let colorEmoji = ["debug": "📘", "log": "📓", "info": "📔", "warn": "📙", "error": "📕"]
|
mit
|
3903251ed2096fbf80d1f0c617d97aee
| 40.487973 | 269 | 0.702559 | 4.654202 | false | false | false | false |
david-mcqueen/Pulser
|
Heart Rate Monitor - Audio/Zone.swift
|
1
|
1646
|
//
// Zone.swift
// Heart Rate Monitor - Audio
//
// Created by DavidMcQueen on 27/03/2015.
// Copyright (c) 2015 David McQueen. All rights reserved.
//
import Foundation
class Zone{
var Lower:Int;
var Upper:Int;
private var ZoneType:HeartRateZone;
private var ZoneKey:UserDefaultKeys?;
init(_lower: Int, _upper:Int, _zone:HeartRateZone){
Lower = _lower;
Upper = _upper;
ZoneType = _zone;
setZone(_zone);
}
func getZoneValuesAsArray()->[Int]{
return [Lower, Upper]
}
func getZoneForSaving()->[NSString]{
return [
NSString(string: String(format: "%d", Lower)),
NSString(string: String(format: "%d", Upper))
];
}
func getZoneType()->HeartRateZone{
return ZoneType;
}
func getZoneKey()->UserDefaultKeys{
return ZoneKey!;
}
//Set the zone type, and the corresponing UserDefaultsKey
func setZone(_zone: HeartRateZone){
ZoneType = _zone;
switch _zone{
case .Rest:
ZoneKey = UserDefaultKeys.ZoneRest;
case .ZoneOne:
ZoneKey = UserDefaultKeys.ZoneOne;
case .ZoneTwo:
ZoneKey = UserDefaultKeys.ZoneTwo;
case .ZoneThree:
ZoneKey = UserDefaultKeys.ZoneThree;
case .ZoneFour:
ZoneKey = UserDefaultKeys.ZoneFour;
case .ZoneFive:
ZoneKey = UserDefaultKeys.ZoneFive;
case .Max:
ZoneKey = UserDefaultKeys.ZoneMax;
default:
ZoneKey = UserDefaultKeys.Unknown;
}
}
}
|
gpl-3.0
|
0faae4bc4b63089b2d5d990fe2a90e57
| 23.220588 | 61 | 0.567436 | 4.19898 | false | false | false | false |
s1Moinuddin/TextFieldWrapper
|
TextFieldWrapper/Classes/Protocols/Zoomable.swift
|
2
|
2409
|
//
// Zoomable.swift
// TextFieldWrapper
//
// Created by Shuvo on 7/29/17.
// Copyright © 2017 Shuvo. All rights reserved.
//
import UIKit
protocol Zoomable {}
extension Zoomable where Self:UIView {
private func addPerspectiveTransformToParentSubviews() {
let scale: CGFloat = 0.8
var transform3D = CATransform3DIdentity
transform3D.m34 = -1/500
transform3D = CATransform3DScale(transform3D, scale, scale, 1)
//let asdf = self.window?.rootViewController
if let topController = window?.visibleViewController() {
if let parentView = topController.view {
parentView.subviews.forEach({ (mySubview) in
if (mySubview != self && !(mySubview is UIVisualEffectView) && !(mySubview is UITableView)) {
mySubview.setAnchorPoint(anchorPoint: CGPoint(x: 0.5, y: 0.5))
mySubview.layer.transform = transform3D
}
})
}
}
}
private func removePerspectiveTransformFromParentSubviews() {
if let topController = window?.visibleViewController() {
if let parentView = topController.view {
parentView.subviews.forEach({ (mySubview) in
if mySubview != self {
mySubview.layer.transform = CATransform3DIdentity
}
})
}
}
}
func zoomIn(duration:TimeInterval, scale: CGFloat) {
UIView.animate(withDuration: duration) { [weak self] in
self?.backgroundColor = UIColor.white
self?.layer.borderColor = UIColor.gray.cgColor
self?.layer.borderWidth = 2.0
self?.layer.cornerRadius = 4.0
self?.layer.isOpaque = true
self?.transform = CGAffineTransform(scaleX: scale, y: scale)
self?.addPerspectiveTransformToParentSubviews()
}
}
func zoomOut(duration:TimeInterval) {
UIView.animate(withDuration: duration) { [weak self] in
self?.layer.borderColor = UIColor.clear.cgColor
self?.layer.borderWidth = 0
self?.layer.cornerRadius = 0
self?.layer.isOpaque = false
self?.transform = .identity
self?.removePerspectiveTransformFromParentSubviews()
}
}
}
|
mit
|
e3138dd8de9255908de3b70f20f8ddac
| 33.4 | 113 | 0.578904 | 4.944559 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK
|
AviasalesSDKTemplate/Source/HotelsSource/HotelPropertyTypeUtils.swift
|
1
|
2844
|
@objc enum HLHotelPropertyType: NSInteger {
case unknown = 0
case hotel = 1
case apartHotel = 2
case bedAndBreakfast = 3
case apartment = 4
case motel = 5
case guesthouse = 6
case hostel = 7
case resort = 8
case farm = 9
case vacation = 10
case lodge = 11
case villa = 12
case room = 13
func localizedValue() -> String? {
switch self {
case .unknown: return nil
case .hotel: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_HOTEL")
case .apartHotel: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_APART_HOTEL")
case .bedAndBreakfast: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_BED_AND_BREAKFAST")
case .apartment: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_APARTMENT")
case .motel: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_MOTEL")
case .guesthouse: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_GUESTHOUSE")
case .hostel: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_HOSTEL")
case .resort: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_RESORT")
case .farm: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_FARM")
case .vacation: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_VACATION")
case .lodge: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_LODGE")
case .villa: return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_VILLA")
case .room : return NSLS("HOTEL_DETAILS_HOTEL_PROPERTY_TYPE_ROOM")
}
}
static let wholePropertyValues: Set<HLHotelPropertyType> = [unknown, hotel, apartHotel, bedAndBreakfast, apartment, motel, guesthouse, hostel, resort, farm, vacation, lodge, villa]
static let roomValues: Set<HLHotelPropertyType> = [room]
static let apartmentValues: Set<HLHotelPropertyType> = [apartHotel, apartment, guesthouse, farm, vacation, villa]
static let hotelValues: Set<HLHotelPropertyType> = [unknown, hotel, bedAndBreakfast, motel, resort, lodge]
static let hostelValues: Set<HLHotelPropertyType> = [hostel]
}
class HotelPropertyTypeUtils: NSObject {
class func localizedHotelPropertyType(_ hotel: HDKHotel) -> String? {
let hotelPropertyEnum = HotelPropertyTypeUtils.hotelPropertyTypeEnum(hotel)
return hotelPropertyEnum.localizedValue()
}
class func hotelPropertyType(_ hotel: HDKHotel) -> String {
let types = ["Unknown", "Hotel", "Apart-hotel", "Bed&Breakfast", "Apartment", "Motel",
"Guesthouse", "Hostel", "Resort", "Farm", "Vacation", "Lodge", "Villa", "Room"]
return hotel.type < types.count ? types[hotel.type] : "Unknown"
}
class func hotelPropertyTypeEnum(_ hotel: HDKHotel) -> HLHotelPropertyType {
return HLHotelPropertyType(rawValue: hotel.type) ?? .unknown
}
}
|
mit
|
90a33c4124ba1f1254dbe2a635a38e8d
| 45.622951 | 184 | 0.675809 | 3.618321 | false | false | false | false |
qkrqjadn/BWTVController
|
BWTVController/Classes/BWTVHeaderView.swift
|
1
|
2445
|
//Copyright (c) 2017 qkrqjadn <qjadn0914@naver.com>
//
//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
public enum expandType {
case expand
case reduce
}
open class BWTVHeaderView: UIView {
open var arrowImg: UIImageView = {
var img = UIImageView()
img.translatesAutoresizingMaskIntoConstraints = false
return img
}()
open var expandState: expandType = .reduce{
didSet{
UIView.animate(withDuration: 0.2) {
if self.expandState == .reduce{
self.arrowImg.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi/180))
} else {
self.arrowImg.transform = CGAffineTransform(rotationAngle: CGFloat(-180 * Double.pi/180) )
}
}
}
}
open var childRows: Int?
public override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(arrowImg)
if #available(iOS 9.0, *) {
self.arrowImg.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -10).isActive = true
self.arrowImg.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
} else {
// Fallback on earlier versions
}
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
dc4e5eed449ccad40c4f0da150be6dc6
| 34.955882 | 110 | 0.671166 | 4.639469 | false | false | false | false |
younata/RSSClient
|
TethysAppSpecs/Helpers/Fakes/FakeUserDefaults.swift
|
1
|
2735
|
import Foundation
class FakeUserDefaults: UserDefaults {
private var internalDictionary: [String: Any] = [:]
init() {
super.init(suiteName: nil)!
}
override init?(suiteName suitename: String?) {
super.init(suiteName: suitename)
}
override func object(forKey defaultName: String) -> Any? {
return self.internalDictionary[defaultName]
}
override func set(_ value: Any?, forKey defaultName: String) {
self.internalDictionary[defaultName] = value
}
override func removeObject(forKey defaultName: String) {
self.internalDictionary.removeValue(forKey: defaultName)
}
override func string(forKey defaultName: String) -> String? {
return self.internalDictionary[defaultName] as? String
}
override func array(forKey defaultName: String) -> [Any]? {
return self.internalDictionary[defaultName] as? [Any]
}
override func dictionary(forKey defaultName: String) -> [String: Any]? {
return self.internalDictionary[defaultName] as? [String: Any]
}
override func data(forKey defaultName: String) -> Data? {
return self.internalDictionary[defaultName] as? Data
}
override func stringArray(forKey defaultName: String) -> [String]? {
return self.internalDictionary[defaultName] as? [String]
}
override func integer(forKey defaultName: String) -> Int {
return self.internalDictionary[defaultName] as? Int ?? 0
}
override func float(forKey defaultName: String) -> Float {
return self.internalDictionary[defaultName] as? Float ?? 0.0
}
override func double(forKey defaultName: String) -> Double {
return self.internalDictionary[defaultName] as? Double ?? 0.0
}
override func bool(forKey defaultName: String) -> Bool {
return self.internalDictionary[defaultName] as? Bool ?? false
}
override func url(forKey defaultName: String) -> URL? {
return self.internalDictionary[defaultName] as? URL
}
override func set(_ value: Int, forKey defaultName: String) {
self.internalDictionary[defaultName] = value
}
override func set(_ value: Float, forKey defaultName: String) {
self.internalDictionary[defaultName] = value
}
override func set(_ value: Double, forKey defaultName: String) {
self.internalDictionary[defaultName] = value
}
override func set(_ value: Bool, forKey defaultName: String) {
self.internalDictionary[defaultName] = value
}
override func set(_ url: URL?, forKey defaultName: String) {
self.internalDictionary[defaultName] = url
}
override func synchronize() -> Bool {
return true
}
}
|
mit
|
c9118e356ed5660c1146c4750d066e99
| 29.388889 | 76 | 0.667642 | 4.635593 | false | false | false | false |
mlmc03/SwiftFM-DroidFM
|
SwiftFM/SwiftFM/Variables.swift
|
1
|
943
|
//
// Variables.swift
// SwiftFM
//
// Created by Mary Martinez on 6/27/16.
// Copyright © 2016 MMartinez. All rights reserved.
//
import Foundation
struct Variables {
static let fmUsername = "admin"
static let fmPassword = "password"
static let hostUsername = "admin"
static let hostPassword = "password"
static let host = "myHost.net"
static let fmIP = Variables.getHost(fmUsername, password: fmPassword)
static let hostIP = Variables.getHost(hostUsername, password: hostPassword)
static let fmXml = "/fmi/xml/fmresultset.xml?-db=swiftfm&-lay=person"
static let findall = "&-findall"
static let myPeople = "\(fmIP)\(fmXml)\(findall)"
static let fmScript = "-script=createRecordWithImage&-script.param="
static let phpScript = "/uploadImage.php"
static func getHost(username: String, password: String) -> String {
return "https://\(username):\(password)@\(host)"
}
}
|
apache-2.0
|
85830b7b186d6cbfc8eed4ff900521d8
| 32.678571 | 79 | 0.683652 | 3.679688 | false | false | false | false |
cubixlabs/GIST-Framework
|
GISTFramework/Classes/BaseClasses/BaseUINavigationController.swift
|
1
|
8938
|
//
// BaseUINavigationController.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/06/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/// BaseUINavigationController is a subclass of UINavigationController. It has some extra proporties and support for SyncEngine.
open class BaseUINavigationController: UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate {
//MARK: - Properties
/// Flag for whether to resize the values for iPad.
@IBInspectable open var sizeForIPad:Bool = GIST_CONFIG.sizeForIPad;
/// Navigation background Color key from SyncEngine.
@IBInspectable open var bgColor:String? = nil {
didSet {
self.navigationBar.barTintColor = SyncedColors.color(forKey:bgColor);
//Fixing black line issue when the navigation is transparent
if self.navigationBar.barTintColor?.cgColor.alpha == 0 {
self.hasSeparator = false;
}
}
} //P.E.
/// Navigation tint Color key from SyncEngine.
@IBInspectable open var tintColor:String? = nil {
didSet {
self.navigationBar.tintColor = SyncedColors.color(forKey:tintColor);
}
} //P.E.
/// Font name key from Sync Engine.
@IBInspectable open var fontName:String = GIST_CONFIG.fontName {
didSet {
var attrDict:[NSAttributedString.Key : Any] = self.navigationBar.titleTextAttributes ?? [NSAttributedString.Key : Any]()
attrDict[NSAttributedString.Key.font] = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
self.navigationBar.titleTextAttributes = attrDict;
}
} //P.E.
@IBInspectable open var largeFontName:String = GIST_CONFIG.fontName {
didSet {
if #available(iOS 11.0, *) {
var attrDict:[NSAttributedString.Key : Any] = self.navigationBar.largeTitleTextAttributes ?? [NSAttributedString.Key : Any]()
attrDict[NSAttributedString.Key.font] = UIFont.font(largeFontName, fontStyle: largeFontStyle, sizedForIPad: self.sizeForIPad);
self.navigationBar.largeTitleTextAttributes = attrDict
}
}
} //P.E.
/// Font size/style key from Sync Engine.
@IBInspectable open var fontStyle:String = GIST_CONFIG.fontStyle {
didSet {
var attrDict:[NSAttributedString.Key : Any] = self.navigationBar.titleTextAttributes ?? [NSAttributedString.Key : Any]()
attrDict[NSAttributedString.Key.font] = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
self.navigationBar.titleTextAttributes = attrDict;
}
} //P.E.
@IBInspectable open var largeFontStyle:String = GIST_CONFIG.largeFontStyle {
didSet {
if #available(iOS 11.0, *) {
var attrDict:[NSAttributedString.Key : Any] = self.navigationBar.largeTitleTextAttributes ?? [NSAttributedString.Key : Any]()
attrDict[NSAttributedString.Key.font] = UIFont.font(largeFontName, fontStyle: largeFontStyle, sizedForIPad: self.sizeForIPad);
self.navigationBar.largeTitleTextAttributes = attrDict
} else {
// Fallback on earlier versions
};
}
} //P.E.
/// Font color key from Sync Engine.
@IBInspectable open var fontColor:String? = nil {
didSet {
var attrDict:[NSAttributedString.Key : Any] = self.navigationBar.titleTextAttributes ?? [NSAttributedString.Key : Any]();
attrDict[NSAttributedString.Key.foregroundColor] = SyncedColors.color(forKey: fontColor);
self.navigationBar.titleTextAttributes = attrDict;
if #available(iOS 11.0, *) {
var lAttrDict:[NSAttributedString.Key : Any] = self.navigationBar.largeTitleTextAttributes ?? [NSAttributedString.Key : Any]()
lAttrDict[NSAttributedString.Key.foregroundColor] = SyncedColors.color(forKey: fontColor);
self.navigationBar.largeTitleTextAttributes = lAttrDict
}
}
} //P.E.
/// Flag for Navigation Separator Line - default value is true
@IBInspectable open var hasSeparator:Bool = true {
didSet {
if (!hasSeparator) {
self.navigationBar.setBackgroundImage(UIImage(), for: .default);
self.navigationBar.shadowImage = UIImage();
} else {
self.navigationBar.setBackgroundImage(nil, for: .default);
self.navigationBar.shadowImage = nil;
}
}
} //P.E.
/// Flag for Navigation bar Shadow - default value is false
@IBInspectable open var shadow:Bool = false {
didSet {
if (shadow != oldValue) {
if (shadow) {
self.navigationBar.layer.shadowColor = UIColor.black.cgColor;
self.navigationBar.layer.shadowOffset = CGSize(width:2.0, height:2.0);
self.navigationBar.layer.shadowRadius = 3.0; //Default is 3.0
self.navigationBar.layer.shadowOpacity = 1.0;
} else {
self.navigationBar.layer.shadowOpacity = 0.0;
}
}
}
} //P.E.
private (set) var _completion:((Bool, Any?) -> Void)?
//MARK: - Constructors
/// Overridden constructor to setup/ initialize components.
///
/// - Parameter rootViewController: Root View Controller of Navigation
override public init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController);
} //F.E.
/// Overridden constructor to setup/ initialize components.
///
/// - Parameters:
/// - nibNameOrNil: Nib Name
/// - nibBundleOrNil: Nib Bundle Name
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil);
} //F.E.
/// Required constructor implemented.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!;
} //F.E.
//MARK: - Overridden Methods
/// Overridden method to setup/ initialize components.
override open func viewDidLoad() {
super.viewDidLoad();
self.setupInteractivePop();
self.updateAppearance();
} //F.E.
/// Overridden method to receive memory warning.
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
} //F.E.
//MARK: - Methods
private func setupInteractivePop() {
self.delegate = self;
self.interactivePopGestureRecognizer?.delegate = self;
} //F.E.
/// Updating the appearance of Navigation Bar.
private func updateAppearance() {
//Update Font
var attrDict:[NSAttributedString.Key : Any] = self.navigationBar.titleTextAttributes ?? [NSAttributedString.Key : Any]()
attrDict[NSAttributedString.Key.font] = UIFont.font(fontName, fontStyle: fontStyle, sizedForIPad: self.sizeForIPad);
self.navigationBar.titleTextAttributes = attrDict;
if #available(iOS 11.0, *) {
var attrDict:[NSAttributedString.Key : Any] = self.navigationBar.titleTextAttributes ?? [NSAttributedString.Key : Any]()
attrDict[NSAttributedString.Key.font] = UIFont.font(largeFontName, fontStyle: largeFontStyle, sizedForIPad: self.sizeForIPad);
self.navigationBar.largeTitleTextAttributes = attrDict
}
//Re-assigning if there are any changes from server
if let newBgColor = bgColor {
self.bgColor = newBgColor;
}
if let newTintColor = tintColor {
self.tintColor = newTintColor;
}
if let newFontColor = fontColor {
self.fontColor = newFontColor;
}
} //F.E.
//Completion Blocks
open func setOnCompletion(completion: @escaping (_ success:Bool, _ data:Any?) -> Void) {
_completion = completion;
} //F.E.
open func completion(_ success:Bool, _ data:Any?) {
_completion?(success, data);
} //F.E.
///MARK:- Delegate Methods
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true;
} //F.E.
open func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
self.interactivePopGestureRecognizer?.isEnabled = self.viewControllers.count > 1;
} //F.E.
} //CLS END
|
agpl-3.0
|
d950c11aba9aa801b1de88215d04210f
| 39.076233 | 153 | 0.624706 | 5.183875 | false | false | false | false |
HotSwitch/FeatureSwitch
|
FeatureSwitch/FeatureManager.swift
|
1
|
2037
|
//
// FeatureManager.swift
// Pods
//
// Created by Ravel Antunes on 4/12/16.
//
//
import UIKit
@objc open class FeatureManager: NSObject {
@objc open static let sharedInstance: FeatureManager = {
return FeatureManager()
}()
fileprivate var featureSet: Set<String>
fileprivate var featureExecutionMap: [String: [(()->())]] = [:]
@objc public override init() {
featureSet = Set<String>()
super.init()
}
@objc public init(featureSet: Set<String>) {
self.featureSet = featureSet
super.init()
}
@objc open func whenEnabled(_ featureName: String, run: @escaping () -> Void) {
if isFeatureEnabled(featureName) {
//Run right away if feature is enabled
run()
} else {
//If not enabled, either add to existing array of functions, or create a new array
if var featureExecutions = featureExecutionMap[featureName] {
featureExecutions.append(run)
featureExecutionMap[featureName] = featureExecutions
} else {
featureExecutionMap[featureName] = [run]
}
}
}
@objc open func ifFeatureEnabled(_ featureName: String, run: () -> Void) {
guard isFeatureEnabled(featureName) else {
return
}
run()
}
//MARK: - TOGGLING AND VERIFICATION
@objc open func enableFeature(_ featureName: String) {
featureSet.insert(featureName)
guard let executions = featureExecutionMap[featureName] else {
return
}
executions.forEach({ (block: (() -> ())) -> () in
print("executing for \(featureName)")
block()
})
}
@objc open func disableFeature(_ featureName: String) {
featureSet.remove(featureName)
}
@objc open func isFeatureEnabled(_ featureName: String) -> Bool {
return featureSet.contains(featureName)
}
}
|
mit
|
62995ac02d30e2920858189e193eb9f1
| 25.802632 | 94 | 0.568974 | 4.693548 | false | false | false | false |
dymx101/Gamers
|
Gamers/Views/HomeController.swift
|
1
|
43930
|
//
// HomeController.swift
// Gamers
//
// Created by 虚空之翼 on 15/7/13.
// Copyright (c) 2015年 Freedom. All rights reserved.
//
import UIKit
import SDCycleScrollView
import MBProgressHUD
import MJRefresh
import Bolts
import SnapKit
import Social
import ReachabilitySwift
class HomeController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView! //滚动视图
@IBOutlet weak var contentView: UIView! //滚动试图内容
let userDefaults = NSUserDefaults.standardUserDefaults() //用户全局登入信息
// 轮播视图及变量
var cycleScrollView: SDCycleScrollView!
var cycleTitles: [String] = []
var cycleImagesURLStrings: [String] = [];
var sliderListData: [Slider] = [Slider]()
//新手推荐视图
var newChannelView: UITableView!
//游戏大咖视图
var featuredChannelView: UITableView!
// 4个热门游戏视图
var hotGameView1: UITableView!
var hotGameView2: UITableView!
var hotGameView3: UITableView!
var hotGameView4: UITableView!
// 3个新游戏视图
var newGameView1: UITableView!
var newGameView2: UITableView!
var newGameView3: UITableView!
// 全局数据 //todo 整合在一起,
var newChannelVideoData = [Video]()
var featuredChannelVideoData = [Video]()
var hotGameData = [Game]()
var newGameData = [Game]()
var hotGame1 = Game()
var hotGame2 = Game()
var hotGame3 = Game()
var hotGame4 = Game()
var newGame1 = Game()
var newGame2 = Game()
var newGame3 = Game()
var hotGameVideo1 = Video()
var hotGameVideo2 = Video()
var hotGameVideo3 = Video()
var hotGameVideo4 = Video()
var newGameVideo1 = Video()
var newGameVideo2 = Video()
var newGameVideo3 = Video()
var gameListData = [Game]()
var videoListData = [Int: [Video]]()
var gamesName = [ 101: "", 102: "", 103: "", 104: "", 105: "", 106: "", 107: "", 108: "", 109: "" ]
var gamesImage = [ 101: "", 102: "", 103: "", 104: "", 105: "", 106: "", 107: "", 108: "", 109: "" ]
// 表格展开状态标记
var expansionStatus = [ 101: false, 102: false, 103: false, 104: false, 105: false, 106: false, 107: false, 108: false, 109: false ]
// 表格移动状态标记
var moveStatus = [ 101: 0, 102: 0, 103: 0, 104: 0, 105: 0, 106: 0, 107: 0, 108: 0, 109: 0 ]
// 刷新数据计数
var refresh = 0
var isStartUp = true
var logoView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// 设定启动界面时间
NSThread.sleepForTimeInterval(0.5)//延长3秒
// 子页面的导航栏返回按钮文字,可为空(去掉按钮文字)
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
// 顶部图标
navigationItem.title = "" //去掉文字,改用图标
navigationController?.navigationBar.backgroundImageForBarMetrics(UIBarMetrics.Default)
logoView = UIImageView(image: UIImage(named: "Gamers-logo"))
navigationController?.navigationBar.addSubview(logoView)
logoView.snp_makeConstraints { (make) -> Void in
make.height.equalTo(28)
make.width.equalTo(82)
make.center.equalTo(navigationController!.navigationBar)
}
//navigationController?.navigationBar.subviews.map ({ $0.removeFromSuperview() })
// navigationController?.navigationBar.removeFromSuperview()
// 下拉刷新数据
scrollView.header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewData")
//scrollView.footer.hidden = true
// 0、顶部轮播
cycleScrollView = SDCycleScrollView(frame: CGRectMake(0, 0, self.view.frame.width, 160), imagesGroup: nil)
cycleScrollView.backgroundColor = UIColor.grayColor()
// 轮播视图的基本属性
cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight
cycleScrollView.infiniteLoop = true;
cycleScrollView.delegate = self
cycleScrollView.dotColor = UIColor.yellowColor() // 自定义分页控件小圆标颜色
cycleScrollView.autoScrollTimeInterval = 4.0
cycleScrollView.placeholderImage = UIImage(named: "sliders.png")
contentView.addSubview(cycleScrollView)
// 4个热门游戏,3个新游戏
createGameTableView()
videoListData[101] = [Video]()
videoListData[102] = [Video]()
videoListData[103] = [Video]()
videoListData[104] = [Video]()
videoListData[105] = [Video]()
videoListData[106] = [Video]()
videoListData[107] = [Video]()
videoListData[108] = [Video]()
videoListData[109] = [Video]()
// 底部标签栏显示数字
//var items = self.tabBarController?.tabBar.items as! [UITabBarItem]
//items[2].badgeValue = "2"
// 加载数据
self.loadNewData()
// 解决table和scroll混用时,点击事件BUG,(是否有效需要更多测试)
scrollView.panGestureRecognizer.delaysTouchesBegan = true
// 检测更新,暂时取消
//update()
}
// 停止刷新状态
func stopRefensh(){
self.refresh++
if self.refresh >= 4 { //3
self.scrollView.header.endRefreshing()
MBProgressHUD.hideHUDForView(self.navigationController!.view, animated: true)
refresh = 0 // 重置刷新计数
}
}
// 获取数据
func loadNewData() {
// 第一次启动使用MBProgressHUD
if isStartUp {
let hub = MBProgressHUD.showHUDAddedTo(self.navigationController!.view, animated: true)
hub.labelText = NSLocalizedString("Loading...", comment: "加載中...")
isStartUp = false
}
// 后台进程获取数据
SliderBL.sharedSingleton.getHomeSlider().continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
if let sliders = task.result as? [Slider] {
for slider in sliders {
self!.cycleTitles.append(slider.title)
self!.cycleImagesURLStrings.append(slider.imageSmall)
}
self!.sliderListData = sliders
}
self!.cycleScrollView.titlesGroup = self!.cycleTitles
self!.cycleScrollView.imageURLStringsGroup = self!.cycleImagesURLStrings
// 重置轮播数据,等待刷新
self!.cycleTitles = []
self!.cycleImagesURLStrings = [];
return nil
}).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
if task.error != nil { println(task.error) }
self!.stopRefensh()
return nil
})
// 新手频道推荐数据
ChannelBL.sharedSingleton.getRecommendChannel(channelType: "new", offset: 1, count: 6, order: "date").continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
if let videoData = (task.result as? [Video]) {
self!.videoListData[101] = videoData
self!.newChannelVideoData = videoData
}
self!.newChannelView.reloadData()
return nil
}).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
if task.error != nil { println(task.error) }
self!.stopRefensh()
return nil
})
// 游戏大咖频道推荐数据
ChannelBL.sharedSingleton.getFollowers(limit: 6, videoCount: 1).continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
if let videoData = (task.result as? [Video]) {
self!.videoListData[102] = videoData
self!.featuredChannelVideoData = videoData
}
self!.featuredChannelView.reloadData()
return nil
}).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
if task.error != nil { println(task.error) }
self!.stopRefensh()
return nil
})
// 推荐游戏数据
hotGameData.removeAll(keepCapacity: false)
newGameData.removeAll(keepCapacity: false)
GameBL.sharedSingleton.getRecommendGame().continueWithSuccessBlock ({ [weak self] (task: BFTask!) -> BFTask! in
if let games = task.result as? [Game] {
self?.gameListData = games
for game in games {
if game.type == "popular" {
self!.hotGameData.append(game)
} else {
self!.newGameData.append(game)
}
}
//println(self!.hotGameData[0].videos)
// 热门游戏
for index in 103...106 {
self!.gamesName[index] = games[index-103].localName
self!.gamesImage[index] = games[index-103].imageSource
self!.videoListData[index] = games[index-103].videos
let view = self!.view.viewWithTag(index) as! UITableView
view.reloadData()
}
// 新游戏
for index in 107...109 {
self!.videoListData[index] = games[index-103].videos
self!.gamesName[index] = games[index-103].localName
self!.gamesImage[index] = games[index-103].imageSource
let view = self!.view.viewWithTag(index) as! UITableView
view.reloadData()
}
}
return nil
}).continueWithBlock({ [weak self] (task: BFTask!) -> BFTask! in
if task.error != nil { println(task.error) }
self!.stopRefensh()
return nil
})
}
// 视图下移
func moveView(tableView: UITableView) {
let viewTag = tableView.tag
// 该tableView以及扩展
expansionStatus[viewTag] = true
// 扩展动画
UIView.animateWithDuration(1, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
self.view.viewWithTag(viewTag)?.frame.size.height = 700
// 后面tableview都下移
for var index = viewTag + 1; index <= 109; index++ {
var moveHeight = (self.moveStatus[index]! + 1) * 300
self.moveStatus[index]! += 1
self.view.viewWithTag(index)?.transform = CGAffineTransformMakeTranslation(0, CGFloat(moveHeight))
}
self.view.viewWithTag(viewTag)!.snp_updateConstraints(closure: { (make) -> Void in
make.height.equalTo(700)
})
}, completion: nil)
// 调整整体界面
var total = 0
for (_, item) in expansionStatus {
if item { total += 1 }
}
let height = 3825 + total * 300
self.contentView.frame = CGRectMake(0, 0, self.view.frame.size.width, CGFloat(height))
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, CGFloat(height))
self.view.backgroundColor = UIColor.lightGrayColor()
}
// 创建内容表格
func createGameTableView() {
// 1、添加新手推荐部分
newChannelView = UITableView()
newChannelView.scrollEnabled = false
// 设置边框
newChannelView.layer.borderWidth = 0.3
newChannelView.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if newChannelView.respondsToSelector("setSeparatorInset:") {
newChannelView.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if newChannelView.respondsToSelector("setLayoutMargins:") {
newChannelView.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
newChannelView.delegate = self
newChannelView.dataSource = self
// 注册自定义的Cell
newChannelView.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
newChannelView.registerNib(UINib(nibName: "ChannelHeaderCell", bundle:nil), forCellReuseIdentifier: "ChannelHeaderCell")
newChannelView.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
newChannelView.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
// 添加新手推荐视图
newChannelView.tag = 101
contentView.addSubview(newChannelView)
// 位置布局
newChannelView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(cycleScrollView.snp_bottom).offset(6)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
newChannelView.scrollEnabled = false
// 2、添加大咖推荐部分
// 创建表视图
featuredChannelView = UITableView()
featuredChannelView.scrollEnabled = false
featuredChannelView.layer.borderWidth = 0.3
featuredChannelView.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if featuredChannelView.respondsToSelector("setSeparatorInset:") {
featuredChannelView.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if featuredChannelView.respondsToSelector("setLayoutMargins:") {
featuredChannelView.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
featuredChannelView.delegate = self
featuredChannelView.dataSource = self
// 注册自定义的Cell
featuredChannelView.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
featuredChannelView.registerNib(UINib(nibName: "ChannelHeaderCell", bundle:nil), forCellReuseIdentifier: "ChannelHeaderCell")
featuredChannelView.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
featuredChannelView.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
// 添加大咖推荐视图
featuredChannelView.tag = 102
contentView.addSubview(featuredChannelView)
// 位置布局
featuredChannelView.snp_makeConstraints { (make) -> Void in
//make.top.equalTo(newChannelView.snp_bottom).offset(6)
make.top.equalTo(contentView).offset(572)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
// 3、热门游戏1
hotGameView1 = UITableView()
hotGameView1.scrollEnabled = false
hotGameView1.layer.borderWidth = 0.3
hotGameView1.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if hotGameView1.respondsToSelector("setSeparatorInset:") {
hotGameView1.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if hotGameView1.respondsToSelector("setLayoutMargins:") {
hotGameView1.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
hotGameView1.delegate = self
hotGameView1.dataSource = self
// 注册自定义的Cell
hotGameView1.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
hotGameView1.registerNib(UINib(nibName: "GameHeaderCell", bundle:nil), forCellReuseIdentifier: "GameHeaderCell")
hotGameView1.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
hotGameView1.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
// 添加热门游戏1视频
hotGameView1.tag = 103
contentView.addSubview(hotGameView1)
// 位置布局
hotGameView1.snp_makeConstraints { (make) -> Void in
//make.top.equalTo(featuredChannelView.snp_bottom).offset(6)
make.top.equalTo(contentView).offset(978)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
// 4、热门游戏2
hotGameView2 = UITableView()
hotGameView2.scrollEnabled = false
hotGameView2.layer.borderWidth = 0.3
hotGameView2.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if hotGameView2.respondsToSelector("setSeparatorInset:") {
hotGameView2.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if hotGameView2.respondsToSelector("setLayoutMargins:") {
hotGameView2.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
hotGameView2.delegate = self
hotGameView2.dataSource = self
// 注册自定义的Cell
hotGameView2.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
hotGameView2.registerNib(UINib(nibName: "GameHeaderCell", bundle:nil), forCellReuseIdentifier: "GameHeaderCell")
hotGameView2.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
hotGameView2.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
hotGameView2.tag = 104
contentView.addSubview(hotGameView2)
// 位置布局
hotGameView2.snp_makeConstraints { (make) -> Void in
//make.top.equalTo(hotGameView1.snp_bottom).offset(6)
make.top.equalTo(contentView).offset(1384)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
// 5、热门游戏3
hotGameView3 = UITableView()
hotGameView3.scrollEnabled = false
hotGameView3.layer.borderWidth = 0.3
hotGameView3.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if hotGameView3.respondsToSelector("setSeparatorInset:") {
hotGameView3.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if hotGameView3.respondsToSelector("setLayoutMargins:") {
hotGameView3.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
hotGameView3.delegate = self
hotGameView3.dataSource = self
// 注册自定义的Cell
hotGameView3.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
hotGameView3.registerNib(UINib(nibName: "GameHeaderCell", bundle:nil), forCellReuseIdentifier: "GameHeaderCell")
hotGameView3.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
hotGameView3.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
hotGameView3.tag = 105
contentView.addSubview(hotGameView3)
// 位置布局
hotGameView3.snp_makeConstraints { (make) -> Void in
//make.top.equalTo(hotGameView2.snp_bottom).offset(6)
make.top.equalTo(contentView).offset(1790)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
// 6、热门游戏4
hotGameView4 = UITableView()
hotGameView4.scrollEnabled = false
hotGameView4.layer.borderWidth = 0.3
hotGameView4.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if hotGameView4.respondsToSelector("setSeparatorInset:") {
hotGameView4.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if hotGameView4.respondsToSelector("setLayoutMargins:") {
hotGameView4.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
hotGameView4.delegate = self
hotGameView4.dataSource = self
// 注册自定义的Cell
hotGameView4.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
hotGameView4.registerNib(UINib(nibName: "GameHeaderCell", bundle:nil), forCellReuseIdentifier: "GameHeaderCell")
hotGameView4.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
hotGameView4.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
hotGameView4.tag = 106
contentView.addSubview(hotGameView4)
// 位置布局
hotGameView4.snp_makeConstraints { (make) -> Void in
//make.top.equalTo(hotGameView3.snp_bottom).offset(6)
make.top.equalTo(contentView).offset(2196)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
// 7、最新游戏1
newGameView1 = UITableView()
newGameView1.scrollEnabled = false
newGameView1.layer.borderWidth = 0.3
newGameView1.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if newGameView1.respondsToSelector("setSeparatorInset:") {
newGameView1.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if newGameView1.respondsToSelector("setLayoutMargins:") {
newGameView1.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
newGameView1.delegate = self
newGameView1.dataSource = self
// 注册自定义的Cell
newGameView1.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
newGameView1.registerNib(UINib(nibName: "GameHeaderCell", bundle:nil), forCellReuseIdentifier: "GameHeaderCell")
newGameView1.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
newGameView1.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
newGameView1.tag = 107
contentView.addSubview(newGameView1)
// 位置布局
newGameView1.snp_makeConstraints { (make) -> Void in
//make.top.equalTo(hotGameView4.snp_bottom).offset(6)
make.top.equalTo(contentView).offset(2602)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
// 8、最新游戏2
newGameView2 = UITableView()
newGameView2.scrollEnabled = false
newGameView2.layer.borderWidth = 0.3
newGameView2.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if newGameView2.respondsToSelector("setSeparatorInset:") {
newGameView2.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if newGameView2.respondsToSelector("setLayoutMargins:") {
newGameView2.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
newGameView2.delegate = self
newGameView2.dataSource = self
// 注册自定义的Cell
newGameView2.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
newGameView2.registerNib(UINib(nibName: "GameHeaderCell", bundle:nil), forCellReuseIdentifier: "GameHeaderCell")
newGameView2.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
newGameView2.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
newGameView2.tag = 108
contentView.addSubview(newGameView2)
// 位置布局
newGameView2.snp_makeConstraints { (make) -> Void in
//make.top.equalTo(newGameView1.snp_bottom).offset(6)
make.top.equalTo(contentView).offset(3008)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
// 9、最新游戏3
newGameView3 = UITableView()
newGameView3.scrollEnabled = false
newGameView3.layer.borderWidth = 0.3
newGameView3.layer.borderColor = UIColor.grayColor().CGColor
// cell分割线边距,ios8处理
if newGameView3.respondsToSelector("setSeparatorInset:") {
newGameView3.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if newGameView3.respondsToSelector("setLayoutMargins:") {
newGameView3.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
// 继承代理和数据源协议
newGameView3.delegate = self
newGameView3.dataSource = self
// 注册自定义的Cell
newGameView3.registerNib(UINib(nibName: "HomeVideoCell", bundle:nil), forCellReuseIdentifier: "HomeVideoCell")
newGameView3.registerNib(UINib(nibName: "GameHeaderCell", bundle:nil), forCellReuseIdentifier: "GameHeaderCell")
newGameView3.registerNib(UINib(nibName: "TableFooterCell", bundle:nil), forCellReuseIdentifier: "TableFooterCell")
newGameView3.registerNib(UINib(nibName: "TableFooterAllCell", bundle:nil), forCellReuseIdentifier: "TableFooterAllCell")
newGameView3.tag = 109
contentView.addSubview(newGameView3)
// 位置布局
newGameView3.snp_makeConstraints { (make) -> Void in
//make.top.equalTo(newGameView2.snp_bottom).offset(6)
make.top.equalTo(contentView).offset(3414)
make.left.equalTo(contentView).offset(6)
make.right.equalTo(contentView).offset(-6)
make.height.equalTo(400)
}
}
// 检测更新
func update() {
SystemBL.sharedSingleton.getVersion().continueWithSuccessBlock({ [weak self] (task: BFTask!) -> BFTask! in
if var version = (task.result as? Version) {
let plistPath = NSBundle.mainBundle().pathForResource("system", ofType: "plist")
//获取属性列表文件中的全部数据
let systemData = NSDictionary(contentsOfFile: plistPath!)!
let localVersion = systemData["version"] as! String
if version.version.toInt() > localVersion.toInt() {
var actionSheetController: UIAlertController = UIAlertController(title: "", message: NSLocalizedString("The new version is detected, whether the update!", comment: "检测到新版本,是否更新!"), preferredStyle: UIAlertControllerStyle.Alert)
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("No", comment: "否"), style: UIAlertActionStyle.Cancel, handler: { (alertAction) -> Void in
//
}))
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Yes", comment: "是"), style: UIAlertActionStyle.Default, handler: { (alertAction) -> Void in
//
}))
// 显示Sheet
self!.presentViewController(actionSheetController, animated: true, completion: nil)
}
}
return nil
})
}
/**
初始化全局尺寸
*/
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
var total = 0
for (_, item) in expansionStatus {
if item { total = total + 1 }
}
let height = 3825 + total * 300
self.contentView.frame = CGRectMake(0, 0, self.view.frame.size.width, CGFloat(height))
self.scrollView.contentSize = CGSizeMake(self.view.frame.size.width, CGFloat(height))
self.view.backgroundColor = UIColor.lightGrayColor()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
//navigationController?.navigationBar.subviews.map ({ $0.removeFromSuperview() })
// navigationController?.navigationBar.removeFromSuperview()
//logoView.removeFromSuperview()
logoView.hidden = true //切换隐藏图标
}
override func viewWillAppear(animated: Bool) {
// 播放页面返回后,重置导航条的透明属性,//todo:image_1.jpg需求更换下
self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: "image_1.jpg"),forBarMetrics: UIBarMetrics.CompactPrompt)
self.navigationController?.navigationBar.shadowImage = UIImage(named: "image_1.jpg")
self.navigationController?.navigationBar.translucent = false
logoView.hidden = false //切换显示图标
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 表格代理
extension HomeController: UITableViewDelegate, UITableViewDataSource {
// 设置表格行数,展开和不展开两种情况
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if self.videoListData[tableView.tag]!.count == 0 {
return 0
}
if expansionStatus[tableView.tag]! {
return self.videoListData[tableView.tag]!.count + 2
} else {
return 5
}
}
// 设置行高
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return 50
} else if indexPath.row == 4 && !expansionStatus[tableView.tag]! {
return 50
} else if indexPath.row == videoListData[tableView.tag]!.count+1 && expansionStatus[tableView.tag]! {
return 50
} else {
return 100
}
}
// 设置单元格的内容(创建参数indexPath指定的单元)
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let viewTag = tableView.tag
switch indexPath.row {
// 表格头0行处理
case 0 where tableView.isEqual(newChannelView):
let cell = tableView.dequeueReusableCellWithIdentifier("ChannelHeaderCell", forIndexPath: indexPath) as! ChannelHeaderCell
cell.imageView?.image = UIImage(named: "Icon-recommend")
cell.hearderTitle.text = NSLocalizedString("Featured youtuber", comment: "精選玩咖")
return cell
case 0 where tableView.isEqual(featuredChannelView):
let cell = tableView.dequeueReusableCellWithIdentifier("ChannelHeaderCell", forIndexPath: indexPath) as! ChannelHeaderCell
cell.imageView?.image = UIImage(named: "Icon-great")
cell.hearderTitle.text = NSLocalizedString("Hot youtuber", comment: "热门大咖")
return cell
case 0:
let cell = tableView.dequeueReusableCellWithIdentifier("GameHeaderCell", forIndexPath: indexPath) as! GameHeaderCell
cell.gameName.text = gamesName[viewTag]
if viewTag <= 106 {
cell.gameDetail.text = NSLocalizedString("Featured games recommended", comment: "熱門遊戲推薦")
} else {
cell.gameDetail.text = NSLocalizedString("Hot games recommended", comment: "精選遊戲推薦")
}
let imageUrl = self.gamesImage[viewTag]!.stringByReplacingOccurrencesOfString(" ", withString: "%20", options: NSStringCompareOptions.LiteralSearch, range: nil)
cell.gameImage.hnk_setImageFromURL(NSURL(string: imageUrl)!, placeholder: UIImage(named: "game-front-cover.png"))
return cell
// 表格底部最后行处理
case 4 where !expansionStatus[viewTag]!:
let cell = tableView.dequeueReusableCellWithIdentifier("TableFooterCell", forIndexPath: indexPath) as! TableFooterCell
return cell
case videoListData[viewTag]!.count+1 where expansionStatus[viewTag]!:
let cell = tableView.dequeueReusableCellWithIdentifier("TableFooterAllCell", forIndexPath: indexPath) as! TableFooterAllCell
return cell
// 中间部分
default :
let cell = tableView.dequeueReusableCellWithIdentifier("HomeVideoCell", forIndexPath: indexPath) as! HomeVideoCell
switch viewTag {
case 101:
cell.setVideo(self.newChannelVideoData[indexPath.row-1])
case 102:
cell.setVideo(self.featuredChannelVideoData[indexPath.row-1])
case 103...106:
cell.setVideo(self.hotGameData[viewTag-103].videos[indexPath.row-1])
case 107...109:
cell.setVideo(self.newGameData[viewTag-107].videos[indexPath.row-1])
default: ()
}
//cell.setVideo(self.videoListData[viewTag]![indexPath.row-1])
cell.delegate = self
cell.tag = viewTag + indexPath.row + 100
return cell
}
}
/**
点击触发,第1个无反应,中间跳转到播放页面,最后一个展开或者跳转到全部视频
*/
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let viewTag = tableView.tag
//println("点击表格-\(viewTag)-触发行: \(indexPath.row)")
if indexPath.row == 0 {
switch viewTag {
case 101:
let viewVC = self.storyboard!.instantiateViewControllerWithIdentifier("ChannelListVC") as? ChannelListController
//viewVC?.viewTag = viewTag
viewVC?.channelType = viewTag == 101 ? "new" : "featured"
self.navigationController?.pushViewController(viewVC!, animated: true)
case 102:
let viewVC = self.storyboard!.instantiateViewControllerWithIdentifier("FollowersListVC") as? FollowersListController
self.navigationController?.pushViewController(viewVC!, animated: true)
case 103...106:
let viewVC = self.storyboard!.instantiateViewControllerWithIdentifier("VideoListVC") as? VideoListController
viewVC?.gameData = hotGameData[viewTag - 103]
self.navigationController?.pushViewController(viewVC!, animated: true)
case 107...109:
let viewVC = self.storyboard!.instantiateViewControllerWithIdentifier("VideoListVC") as? VideoListController
viewVC?.gameData = newGameData[viewTag - 107]
self.navigationController?.pushViewController(viewVC!, animated: true)
default: ()
}
} else if indexPath.row == 4 && !expansionStatus[viewTag]! {
// 移动动画
moveView(tableView)
let dataView = self.view.viewWithTag(viewTag) as! UITableView
dataView.reloadData()
} else if indexPath.row == videoListData[viewTag]!.count + 1 && expansionStatus[viewTag]!{
// 跳转到不同的全部界面
switch viewTag {
case 101:
let viewVC = self.storyboard!.instantiateViewControllerWithIdentifier("ChannelListVC") as? ChannelListController
//viewVC?.viewTag = viewTag
viewVC?.channelType = viewTag == 101 ? "new" : "featured"
self.navigationController?.pushViewController(viewVC!, animated: true)
case 102:
let viewVC = self.storyboard!.instantiateViewControllerWithIdentifier("FollowersListVC") as? FollowersListController
self.navigationController?.pushViewController(viewVC!, animated: true)
case 103...106:
let viewVC = self.storyboard!.instantiateViewControllerWithIdentifier("VideoListVC") as? VideoListController
viewVC?.gameData = hotGameData[viewTag - 103]
self.navigationController?.pushViewController(viewVC!, animated: true)
case 107...109:
let viewVC = self.storyboard!.instantiateViewControllerWithIdentifier("VideoListVC") as? VideoListController
viewVC?.gameData = newGameData[viewTag - 107]
self.navigationController?.pushViewController(viewVC!, animated: true)
default: ()
}
} else {
let view = self.storyboard!.instantiateViewControllerWithIdentifier("PlayerViewVC") as? PlayerViewController
view?.videoData = self.videoListData[viewTag]![indexPath.row-1]
self.navigationController?.pushViewController(view!, animated: true)
}
}
// cell分割线的边距
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if cell.respondsToSelector("setSeparatorInset:") {
cell.separatorInset = UIEdgeInsetsMake(0, 5, 0, 5)
}
if cell.respondsToSelector("setLayoutMargins:") {
cell.layoutMargins = UIEdgeInsetsMake(0, 5, 0, 5)
}
}
}
// MARK: - 顶部轮播的代理方法
extension HomeController: SDCycleScrollViewDelegate {
func cycleScrollView(cycleScrollView: SDCycleScrollView!, didSelectItemAtIndex index: Int) {
var sliderVC = self.storyboard!.instantiateViewControllerWithIdentifier("SliderVC") as? SliderController
sliderVC?.sliderData = sliderListData[index]
self.navigationController?.pushViewController(sliderVC!, animated: true)
}
}
// MARK: - 表格行Cell代理
extension HomeController: MyCellDelegate {
// 触发分享按钮事件
func clickCellButton(sender: UITableViewCell) {
let table = self.view.viewWithTag(sender.superview!.superview!.tag) as! UITableView
let index: NSIndexPath = table.indexPathForCell(sender)!
var video = self.videoListData[sender.tag - index.row - 100]![index.row-1]
// var video = Video()
// println("表格:\(sender.tag - index.row - 100),行:\(index.row)")
// switch sender.tag {
// case 101:
// video = newChannelVideoData[index.row - 1]
// case 102:
// video = featuredChannelVideoData[index.row - 1]
// case 103...106:
// video = hotGameData[sender.tag - index.row - 200].videos[index.row - 1]
// println(video)
// case 107...109:
// video = newGameData[sender.superview!.superview!.tag - index.row - 100].videos[index.row - 1]
// default: ()
//
// }
//
// println(video)
// 退出
var actionSheetController: UIAlertController = UIAlertController()
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: "取消"), style: UIAlertActionStyle.Cancel) { (alertAction) -> Void in
//code
})
// 关注频道
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Follow", comment: "追随"), style: UIAlertActionStyle.Default) { (alertAction) -> Void in
if self.userDefaults.boolForKey("isLogin") {
UserBL.sharedSingleton.setFollow(channelId: video.ownerId)
} else {
var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Please Login", comment: "请先登入"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定"))
alertView.show()
}
})
// 分享到Facebook
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Share on Facebook", comment: "分享到Facebook"), style: UIAlertActionStyle.Default) { (alertAction) -> Void in
var slComposerSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
slComposerSheet.setInitialText(video.videoTitle)
slComposerSheet.addImage(UIImage(named: video.imageSource))
slComposerSheet.addURL(NSURL(string: "https://www.youtube.com/watch?v=\(video.videoId)"))
self.presentViewController(slComposerSheet, animated: true, completion: nil)
SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook)
slComposerSheet.completionHandler = { (result: SLComposeViewControllerResult) in
if result == .Done {
var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Share Finish", comment: "分享完成"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定"))
alertView.show()
}
}
})
// 分享到Twitter
actionSheetController.addAction(UIAlertAction(title: NSLocalizedString("Share on Twitter", comment: "分享到Twitter"), style: UIAlertActionStyle.Default) { (alertAction) -> Void in
var slComposerSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
slComposerSheet.setInitialText(video.videoTitle)
slComposerSheet.addImage(UIImage(named: video.imageSource))
slComposerSheet.addURL(NSURL(string: "https://www.youtube.com/watch?v=\(video.videoId)"))
self.presentViewController(slComposerSheet, animated: true, completion: nil)
slComposerSheet.completionHandler = { (result: SLComposeViewControllerResult) in
if result == .Done {
var alertView: UIAlertView = UIAlertView(title: "", message: NSLocalizedString("Share Finish", comment: "分享完成"), delegate: nil, cancelButtonTitle: NSLocalizedString("OK", comment: "确定"))
alertView.show()
}
}
})
// 显示Sheet
self.presentViewController(actionSheetController, animated: true, completion: nil)
}
}
|
apache-2.0
|
4c9e6a57f8ebb47a2c406930d7902da4
| 41.695122 | 246 | 0.618442 | 4.809616 | false | false | false | false |
ivlevAstef/DITranquillity
|
Sources/Core/Internal/ProtocolMagic.swift
|
1
|
4307
|
//
// ProtocolMagic.swift
// DITranquillity
//
// Created by Alexander Ivlev on 14/06/16.
// Copyright © 2016 Alexander Ivlev. All rights reserved.
//
/// Weak reference
class Weak<T> {
private weak var _value: AnyObject?
var value: T? { return _value as? T }
init(value: T) {
self._value = value as AnyObject
}
}
/// fix bug on xcode 11.2.1, and small improve speed. Don't use Weak<T> for any
class WeakAny {
private(set) weak var value: AnyObject?
init(value: Any) {
self.value = value as AnyObject
}
}
/// For remove optional type
extension Optional: SpecificType {
static var type: DIAType { return Wrapped.self }
static var isSwiftType: Bool { return true }
static var optional: Bool { return true }
static func make(by obj: Any?) -> Optional<Wrapped> {
return obj as? Wrapped
}
}
/// For optional make
func gmake<T>(by obj: Any?) -> T {
if let opt = T.self as? SpecificType.Type {
guard let typedObject = opt.make(by: obj) as? T else { // it's always valid
fatalError("Can't cast \(type(of: obj)) to optional \(T.self). For more information see logs.")
}
return typedObject
}
guard let typedObject = obj as? T else {
let unwrapObj = obj.unwrapGet()
guard let typedUnwrapObject = unwrapObj as? T else {
if nil == obj {
fatalError("Can't resolve type \(T.self). For more information see logs.")
} else if nil == unwrapObj { // DI found and return obj, but registration make nil object
fatalError("""
Registration with type found \(T.self), but the registration return nil.
Check you code - maybe in registration method you return nil object. For example:
var obj: Obj? = nil
container.register { obj }
""")
} else {
fatalError("Can't cast \(type(of: obj)) to \(T.self). For more information see logs.")
}
}
return typedUnwrapObject
}
return typedObject
}
protocol OptionalUnwrapper {
static var unwrapType: DIAType { get }
}
extension Optional: OptionalUnwrapper {
static var unwrapType: DIAType { return Wrapped.self }
}
func unwrapType(_ type: DIAType) -> DIAType {
var iter = type
while let unwrap = iter as? OptionalUnwrapper.Type {
iter = unwrap.unwrapType
}
return iter
}
func swiftType(_ type: DIAType) -> DIAType {
var iter = type
while let unwrap = iter as? SpecificType.Type {
iter = unwrap.type
}
return iter
}
/// For simple log
func description(type parsedType: ParsedType) -> String {
if let sType = parsedType.sType {
if sType.tag {
return "type: \(sType.type) with tag: \(sType.tagType)"
} else if sType.many {
return "many with type: \(sType.type)"
}
}
return "type: \(parsedType.type)"
}
/// for get bundle by type
#if swift(>=4.1)
#else
extension Sequence {
@inline(__always)
func compactMap<ElementOfResult>(_ transform: (Element) throws -> ElementOfResult?) rethrows -> [ElementOfResult] {
return try flatMap(transform)
}
}
#endif
// MARK: Swift 4.2
#if swift(>=4.1.5)
#else
extension ImplicitlyUnwrappedOptional: SpecificType {
static var type: DIAType { return Wrapped.self }
static var isSwiftType: Bool { return true }
static func make(by obj: Any?) -> ImplicitlyUnwrappedOptional<Wrapped> {
return obj as? Wrapped
}
}
#endif
protocol GetRealOptional {
func unwrapGet() -> Any?
}
extension Optional: GetRealOptional {
func unwrapGet() -> Any? {
switch self {
case .some(let obj):
if let optObj = obj as? GetRealOptional {
return optObj.unwrapGet()
}
return obj
case .none:
return nil
}
}
}
/// Get that really existed variable. if-let syntax could not properly work with Any?-Any-Optional.some(Optional.none) in swift 4.2+
///
/// - Parameter optionalObject: Object for recursively value getting
/// - Returns: *object* if value really exists. *nil* otherwise.
func getReallyObject(_ optionalObject: Any?) -> Any? {
// Swift 4.2 bug...
#if swift(>=4.1.5)
return optionalObject.unwrapGet()
#else
return optionalObject
#endif
}
extension String {
var fileName: String {
return split(separator: "/").last.flatMap { "\($0)" } ?? self
}
}
|
mit
|
99d9ba7eb3f2e9949fe460514b2f9e5b
| 23.890173 | 132 | 0.642824 | 3.757417 | false | false | false | false |
ggu/2D-RPG-Template
|
Borba/backend/structs/Spell.swift
|
2
|
1196
|
//
// Spell.swift
// Borba
//
// Created by Gabriel Uribe on 8/5/15.
// Copyright (c) 2015 Team Five Three. All rights reserved.
//
struct Spell {
enum String {
static let fireball: SpellString = "fireball"
static let arcaneBolt: SpellString = "arcanebolt"
static let lightningBolt: SpellString = "lightning"
}
enum Name {
case fireball
case arcaneBolt
case lightning
}
enum Damage {
static let fireball = 100.0
static let arcaneBolt = 20.0
static let lightningStorm = 120.0
}
enum Cooldowns {
static let fireball = 0.8
static let arcaneBolt = 0.2
static let lightningStorm = 1.3
}
enum Costs {
static let fireball = 10.0
static let arcaneBolt = 5.0
static let lightningStorm = 50.0
}
enum MissileSpeeds {
static let fireball = 150.0
static let arcaneBolt = 200.0
static let lightningStorm = 80.0
}
var damage: Double
var spellName : Name
var cost: Double
var cooldown: Double
init(spellDamage: Double, spell : Name, spellCost: Double, spellCooldown: Double) {
damage = spellDamage
spellName = spell
cost = spellCost
cooldown = spellCooldown
}
}
|
mit
|
09be386334c4153a29144cb4c5918e4a
| 19.982456 | 85 | 0.654682 | 3.497076 | false | false | false | false |
WhisperSystems/Signal-iOS
|
Signal/src/views/ExpirationNagView.swift
|
1
|
1012
|
//
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import UIKit
class ExpirationNagView: ReminderView {
private static let updateLink = URL(string: "itms-apps://itunes.apple.com/app/id874139669")!
@objc convenience init() {
self.init(mode: .nag, text: "") {
UIApplication.shared.openURL(ExpirationNagView.updateLink)
}
}
@objc func updateText() {
if AppExpiry.isExpired {
text = NSLocalizedString("EXPIRATION_ERROR", comment: "Label notifying the user that the app has expired.")
} else if AppExpiry.daysUntilBuildExpiry == 1 {
text = NSLocalizedString("EXPIRATION_WARNING_TODAY", comment: "Label warning the user that the app will expire today.")
} else {
let soonWarning = NSLocalizedString("EXPIRATION_WARNING_SOON", comment: "Label warning the user that the app will expire soon.")
text = String(format: soonWarning, AppExpiry.daysUntilBuildExpiry)
}
}
}
|
gpl-3.0
|
965a4e1fe67a5547b1ab83df704c3870
| 37.923077 | 140 | 0.662055 | 4.181818 | false | false | false | false |
chengang/iMei
|
iMei/Regex/Utils.swift
|
1
|
1335
|
//===--- Utils.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//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
public typealias StringRange = Range<String.Index>
#if !os(Linux)
extension NSTextCheckingResult {
func range(at idx: Int) -> NSRange {
return rangeAt(idx)
}
}
#endif
extension Sequence where Iterator.Element : Hashable {
var indexHash:Dictionary<Iterator.Element, Int> {
get {
var result = Dictionary<Iterator.Element, Int>()
var index = 0
for e in self {
result[e] = index
index += 1
}
return result
}
}
}
|
lgpl-3.0
|
f372ad5134a82cfbbef2f2661ca3e595
| 31.560976 | 80 | 0.580524 | 4.802158 | false | false | false | false |
urdnot-ios/ShepardAppearanceConverter
|
ShepardAppearanceConverter/ShepardAppearanceConverter/Views/Common/Popover/PopoverSourceHandler.swift
|
1
|
3320
|
//
// PopoverSourceHandler.swift
// ShepardAppearanceConverter
//
// Created by Emily Ivie on 8/19/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import UIKit
/// Example of code needed to implement this protocol:
///
/// var popoverSourceHandler: PopoverSourceHandler?
///
/// override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
/// if let popoverPresentationController = segue.destinationViewController.popoverPresentationController {
/// popoverSourceHandler = PopoverSourceHandler(owner: self, popoverPresentationController: popoverPresentationController)
/// }
/// }
///
// This is not a protocol because protocols have difficulty with also being delegates. The delegate calls never get made :/
public class PopoverSourceHandler: NSObject, UIPopoverPresentationControllerDelegate {
unowned var owner: UIViewController
public init(owner: UIViewController, source: AnyObject?, popoverPresentationController: UIPopoverPresentationController) {
self.owner = owner
super.init()
popoverPresentationController.presentedViewController.preferredContentSize = PopoverValues.PreferredDefaultSize // set later to match loaded content
popoverPresentationController.delegate = self
popoverPresentationController.popoverBackgroundViewClass = PopoverBackgroundView.self
popoverPresentationController.permittedArrowDirections = UIPopoverArrowDirection.Unknown
popoverPresentationController.sourceView = source as? UIView
popoverPresentationController.sourceRect = pickCenterRect(sourceView: source as? UIView, targetSize: PopoverValues.PreferredDefaultSize)
}
func pickCenterRect(sourceView sourceView: UIView?, targetSize: CGSize) -> CGRect {
if sourceView != nil {
var sourcePoint = CGPointMake(sourceView!.frame.origin.x + sourceView!.bounds.width, sourceView!.frame.origin.y + (sourceView!.bounds.height / 2))
var chainView = sourceView!.superview
while chainView != nil && chainView != owner.view {
sourcePoint.x += chainView!.frame.origin.x
sourcePoint.y += chainView!.frame.origin.y
chainView = chainView?.superview
}
sourcePoint.x -= targetSize.width / 2
sourcePoint.x += PopoverValues.MagicNumberCorrectPopoverRight
sourcePoint.y -= targetSize.height / 2
return CGRect(origin: sourcePoint, size: CGSizeMake(1, 1))
}
let sourcePoint = CGPointMake(owner.view.bounds.width / 2, (owner.view.bounds.height / 2))
return CGRect(origin: sourcePoint, size: CGSizeMake(1,1))
}
public func popoverPresentationControllerDidDismissPopover(popoverPresentationController: UIPopoverPresentationController) {
//? nothing to do
}
public func popoverPresentationController(popoverPresentationController: UIPopoverPresentationController, willRepositionPopoverToRect rect: UnsafeMutablePointer<CGRect>, inView view: AutoreleasingUnsafeMutablePointer<UIView?>) {
let size = popoverPresentationController.presentedViewController.view.bounds.size
rect.memory = pickCenterRect(sourceView: popoverPresentationController.sourceView, targetSize: size)
}
}
|
mit
|
ce99ab893b43201492234a2a1c275724
| 52.548387 | 232 | 0.733956 | 5.634975 | false | false | false | false |
sergeyzenchenko/react-swift
|
ReactSwift/ReactSwift/ViewController.swift
|
1
|
3227
|
//
// ViewController.swift
// ReactSwift
//
// Created by Sergey Zenchenko on 11/1/14.
// Copyright (c) 2014 Techery. All rights reserved.
//
import UIKit
func horizontalLayout(block: () -> Void) -> Node {
return Node()
}
func verticalLayout(block: () -> Void) -> Node {
return Node()
}
func padding(left:Int = 0, top:Int = 0, right:Int = 0, bottom:Int = 0) -> Node {
return Node()
}
class StateHolder<S> {
var invalidate:() -> Void
init(state:S) {
self.state = state
self.invalidate = {}
}
var state:S {
didSet {
invalidate()
}
}
}
class TestComponent : Component {
override func render() -> Node {
let view = ViewNode()
view.frame = self.frame
view.backgroundColor = UIColor.greenColor()
return view
}
}
class SampleComponent : Component {
struct State {
let enabled:Bool
}
func state() -> State {
return super.state() as State
}
override func getInitialState() -> StateType {
return State(enabled: false)
}
override func render() -> Node {
let view = LinearLayout()
view.add(Switch(isOn: self.state().enabled) {[weak self] isOn in
self!.setState(State(enabled: isOn))
});
view.add(Switch(isOn: self.state().enabled) {[weak self] isOn in
self!.setState(State(enabled: isOn))
});
view.add(Switch(isOn: self.state().enabled) {[weak self] isOn in
self!.setState(State(enabled: isOn))
});
view.add(Button());
view.frame = CGRectMake(100, 100, 100, 200)
if self.state().enabled {
view.backgroundColor = UIColor.redColor()
}
let testComponent = TestComponent()
testComponent.frame = CGRectMake(0, 50, 100, 30)
view.add(testComponent)
return view
}
}
func ComponentSample(title:String) -> () -> Node {
struct State {
let enabled = false
}
let state = State(enabled: false)
func render() -> Node {
let view = ViewNode()
return view
}
return render
}
class SampleDSLComponent : Component {
override func render() -> Node {
return verticalLayout {
padding(left: 0, top: 10)
horizontalLayout {
ViewNode()
ViewNode()
ViewNode()
}
Button()
}
}
}
class ViewController: UIViewController {
var renderingEngine:RenderingEngine?;
var currentView:UIView? {
willSet(newView) {
if let view = self.currentView {
view.removeFromSuperview()
}
}
didSet {
self.view.addSubview(self.currentView!)
}
}
override func viewDidLoad() {
super.viewDidLoad()
renderingEngine = RenderingEngine({
[weak self]
(view) in
self!.currentView = view
})
renderingEngine!.render(SampleComponent());
}
}
|
mit
|
7573cd9297643bcce06bd57802822969
| 19.819355 | 80 | 0.521537 | 4.55791 | false | false | false | false |
maxep/DiscogsAPI
|
Example-swift/DGReleaseViewController.swift
|
2
|
3089
|
// DGReleaseViewController.swift
//
// Copyright (c) 2017 Maxime Epain
//
// 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
import DiscogsAPI
class DGReleaseViewController: DGViewController {
fileprivate var trackList : [DGTrack]! {
didSet { tableView.reloadData() }
}
override func viewDidLoad() {
super.viewDidLoad()
// Get release details
Discogs.api.database.get(release: objectID, success: { (release) in
self.titleLabel.text = release.title
self.detailLabel.text = release.artists.first?.name
self.yearLabel.text = release.year!.stringValue
self.styleLabel.text = release.genres.joined(separator: ", ")
self.trackList = release.trackList
// Get a Discogs image
if let image = release.images.first, let url = image.resourceURL {
Discogs.api.resource.get(image: url, success: { (image) in
self.coverView?.image = image
})
}
}) { (error) in
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: UITableViewDataSource
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return trackList?.count ?? 0
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "Tracks"
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TrackCell")!
let track = trackList[indexPath.row]
cell.textLabel?.text = (track.position ?? "") + ".\t" + (track.title ?? "")
cell.detailTextLabel?.text = track.duration
return cell
}
}
|
mit
|
de6b03314a7c5b0f5b64193780d67119
| 37.135802 | 109 | 0.652315 | 4.849294 | false | false | false | false |
alexxjk/ProtocolUI.Swift
|
ProtocolUISwift/ProtocolUISwift/IconButtonComponent.swift
|
1
|
1999
|
//
// DefaultIconButton.swift
// ProtocolUISwift
//
// Created by Alexander Martirosov on 14/07/2017.
// Copyright © 2017 Alexander Martirosov. All rights reserved.
//
import UIKit
open class IconButtonComponent : UIComponent<UIView>, UIIconButtonComponentProtocol {
public var iconPath: String
private var icon: UIImageContainerComponentProtocol!
required public init(_ iconPath: String) {
self.iconPath = iconPath
super.init()
self.setupIcon()
let tapGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
tapGesture.minimumPressDuration = 0.001
self.getImplementer().addGestureRecognizer(tapGesture)
}
func setupIcon() {
precondition(self.iconPath.characters.count > 0)
self.icon = try! UIFactory.imageContainerComponentConfigurator()
.withLocalImage(iconPath)
.create()
self.implementer.addSubview(self.icon.getImplementer())
self.icon.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
self.icon.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
self.icon.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
self.icon.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
}
func handleTap(_ sender: UILongPressGestureRecognizer) {
if sender.state == .began {
self.animateIconState(0.5)
} else if sender.state == .ended {
self.animateIconState(1)
self.tapHandler?()
} else if sender.state == .cancelled {
self.animateIconState(1)
}
}
public var tapHandler: (() -> ())?
func animateIconState(_ opacity: Float) {
UIView.animate(withDuration: 0.1, delay: 0, options: [.curveEaseIn], animations: {
self.icon.opacity = opacity
})
}
}
|
mit
|
e3a022090a207b0e4b5f2a687c38315f
| 31.225806 | 106 | 0.635135 | 4.712264 | false | false | false | false |
drewcrawford/DCAKit
|
DCAKit/Foundation Additions/Keychain/BetterKeychain.swift
|
1
|
8046
|
//
// BetterKeychain.swift
// DCAKit
//
// Created by Drew Crawford on 1/18/15.
// Copyright (c) 2015 DrewCrawfordApps.
// This file is part of DCAKit. It is subject to the license terms in the LICENSE
// file found in the top level of this distribution and at
// https://github.com/drewcrawford/DCAKit/blob/master/LICENSE.
// No part of DCAKit, including this file, may be copied, modified,
// propagated, or distributed except according to the terms contained
// in the LICENSE file.
import Foundation
import Security
public let BetterKeychainErrorDomain = "BetterKeychainErrorDomain"
public class BetterKeychain {
public class Error : NSError {
public enum Codes : Int {
case Unimplemented
case Param
case Allocate
case NotAvailable
case AuthFailed
case DuplicateItem
case ItemNotFound
case InteractionNotAllowed
case Decode
case UnknownOSStatus
}
public convenience init(code: Codes, userInfo: [NSObject: AnyObject]?) {
self.init(domain: BetterKeychainErrorDomain, code: code.rawValue, userInfo: userInfo)
}
public convenience init(osStatus: OSStatus) {
var code : Codes? = nil
switch(osStatus) {
case errSecUnimplemented:
code = .Unimplemented
case errSecParam:
code = .Param
case errSecAllocate:
code = .Allocate
case errSecNotAvailable:
code = .NotAvailable
case errSecAuthFailed:
code = .AuthFailed
case errSecDuplicateItem:
code = .DuplicateItem
case errSecItemNotFound:
code = .ItemNotFound
case errSecInteractionNotAllowed:
code = .InteractionNotAllowed
case errSecDecode:
code = .Decode
default:
code = .UnknownOSStatus
}
self.init(domain: BetterKeychainErrorDomain, code: code!.rawValue, userInfo: ["osstatus":Int(osStatus)])
}
}
public enum AccessibilityConstants {
case AfterFirstUnlock
case AfterFirstUnlockThisDeviceOnly
case Always
case AlwaysThisDeviceOnly
case WhenUnlocked
case WhenUnlockedThisDeviceOnly
case WhenPasscodeSetThisDeviceOnly
private var stringValue : String {
get {
switch(self) {
case .AfterFirstUnlock:
return kSecAttrAccessibleAfterFirstUnlock as String
case .AfterFirstUnlockThisDeviceOnly:
return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as String
case .Always:
return kSecAttrAccessibleAlways as String
case .AlwaysThisDeviceOnly:
return kSecAttrAccessibleAlwaysThisDeviceOnly as String
case .WhenUnlocked:
return kSecAttrAccessibleWhenUnlocked as String
case .WhenUnlockedThisDeviceOnly:
return kSecAttrAccessibleWhenUnlockedThisDeviceOnly as String
case .WhenPasscodeSetThisDeviceOnly:
return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as String
}
}
}
private init(stringConstant: String) {
switch(stringConstant) {
case kSecAttrAccessibleAfterFirstUnlock as! String:
self = .AfterFirstUnlock
case kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as! String:
self = .AfterFirstUnlockThisDeviceOnly
case kSecAttrAccessibleAlways as! String:
self = .Always
case kSecAttrAccessibleAlwaysThisDeviceOnly as! String:
self = .AlwaysThisDeviceOnly
case kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly as! String:
self = .WhenPasscodeSetThisDeviceOnly
case kSecAttrAccessibleWhenUnlocked as! String:
self = .WhenUnlocked
case kSecAttrAccessibleWhenUnlockedThisDeviceOnly as! String:
self = .WhenUnlockedThisDeviceOnly
default:
preconditionFailure("Unknown string constant.")
}
}
}
public struct GenericPassword {
public var accessibility : AccessibilityConstants
//todo: accessgroup
//todo: dates
public var description : String? = nil
//todo: comment
//todo: creator
//todo: type
//todo: label
//todo: invisible
//todo: isNegative
public var account: String? = nil
public var service: String? = nil
public var generic: NSData? = nil
var dict : [String: AnyObject] {
get {
var dict : [String: AnyObject] = [:]
dict[kSecClass as String] = kSecClassGenericPassword
dict[kSecAttrAccessible as String] = self.accessibility.stringValue
dict[kSecAttrAccount as String] = self.account
dict[kSecAttrService as String] = self.service
dict[kSecAttrGeneric as String] = self.generic
dict[kSecAttrDescription as String] = self.description
return dict
}
}
private init(dict: [String: AnyObject]) {
accessibility = AccessibilityConstants(stringConstant: dict[kSecAttrAccessible as String] as! String)
description = dict[kSecAttrDescription as String] as? String
account = dict[kSecAttrAccount as String] as? String
service = dict[kSecAttrService as String] as? String
generic = dict[kSecAttrGeneric as String] as? NSData
}
public init(accessibility: AccessibilityConstants) { //rdar://19513640
self.accessibility = accessibility
}
public func add() -> NSError? {
let result = SecItemAdd(dict, nil)
if (result != errSecSuccess) {
return Error(osStatus: result)
}
return nil
}
public func findOne() -> ErrorOr<GenericPassword> {
var ldict : [String: AnyObject] = dict
ldict[kSecMatchLimit as String] = kSecMatchLimitOne
ldict[kSecReturnAttributes as String] = true
var rDict : Unmanaged<AnyObject>?
let rdarResult = secItemCopyMatchingRdar19527311(ldict)
precondition(rdarResult != nil, "BKC internal error")
if rdarResult.status != errSecSuccess {
return ErrorOr(error: Error(osStatus: rdarResult.status))
}
let backDict : ErrorOr<[String: AnyObject]> = Cast(rdarResult.innerResult, label: "innerResult cast")
if (backDict.isError) {
return ErrorOr(error: backDict.error!)
}
let foundToken = GenericPassword(dict: backDict.value!)
return ErrorOr(value: foundToken)
}
public func deleteIfExists() -> NSError? {
let result = delete()
return result?.suppress((domain: BetterKeychainErrorDomain, code: Error.Codes.ItemNotFound.rawValue))
}
public func delete() -> NSError? {
let result = SecItemDelete(dict)
if (result != errSecSuccess) {
return Error(osStatus: result)
}
return nil
}
public func update(#to: GenericPassword) -> NSError? {
var ldict = dict
var rdict = to.dict
rdict[kSecClass as String] = nil
let result = SecItemUpdate(ldict, rdict)
if result != errSecSuccess {
return Error(osStatus: result)
}
return nil
}
}
}
|
mit
|
d28823511c0e5f28e11406b97f7f2f7b
| 38.446078 | 116 | 0.584141 | 6.040541 | false | false | false | false |
startupthekid/Partybus
|
Partybus/Coordinators/MapCoordinator.swift
|
1
|
2042
|
//
// MapCoordinator.swift
// Partybus
//
// Created by Brendan Conron on 11/15/16.
// Copyright © 2016 Swoopy Studios. All rights reserved.
//
import UIKit
import Alamofire
import ReactiveSwift
import Moya_ObjectMapper
import Moya
import Swinject
class MapCoordinator: BaseCoordinator {
// MARK: - Controllers
private let mainMapViewController: MapViewController?
// MARK: - Dependency Injection
private let container = Container { c in
c.register(MapViewController.self) { _ in MapViewController() }
c.register(DispatchQueue.self) { _ in DispatchQueue.global(qos: .utility) }
c.register(MapViewModelProtocol.self) { _ in MapViewModel() }
}
// MARK: - View Model
private let viewModel: MapViewModelProtocol
// MARK: - Queues
let utilityQueue: DispatchQueue?
// MARK: - Initialization
required init(rootViewController: UIViewController) {
mainMapViewController = container.resolve(MapViewController.self)
utilityQueue = container.resolve(DispatchQueue.self)
viewModel = container.resolve(MapViewModelProtocol.self)!
super.init(rootViewController: rootViewController)
}
override func start(_ completion: CoordinatorCompletion?) {
guard let navigationController = rootViewController as? UINavigationController else { return }
guard let destinationController = mainMapViewController else { return }
destinationController.loadViewIfNeeded()
navigationController.setViewControllers([destinationController], animated: false)
viewModel.routes <~ fetchRoutes().flatMapError { _ in .empty }
super.start(completion)
}
// MARK: - Networking
private func fetchRoutes() -> SignalProducer<[Route], Moya.Error> {
return Providers.DoubleMapProvider
.request(token: .routes)
.mapArray(Route.self)
.start(on: QueueScheduler(qos: .utility, name: "com.swoopystudios.partybus.network.api.routes", targeting: utilityQueue))
}
}
|
mit
|
0331c66250f06d2a51c9a9c9ddf7309b
| 30.890625 | 133 | 0.703087 | 4.871122 | false | false | false | false |
kstaring/swift
|
test/attr/accessibility.swift
|
1
|
10211
|
// RUN: %target-parse-verify-swift
// CHECK PARSING
private // expected-note {{modifier already specified here}}
private // expected-error {{duplicate modifier}}
func duplicateAttr() {}
private // expected-note {{modifier already specified here}}
public // expected-error {{duplicate modifier}}
func duplicateAttrChanged() {}
private // expected-note 2 {{modifier already specified here}}
public // expected-error {{duplicate modifier}}
internal // expected-error {{duplicate modifier}}
func triplicateAttrChanged() {}
private // expected-note 3 {{modifier already specified here}}
public // expected-error {{duplicate modifier}}
internal // expected-error {{duplicate modifier}}
fileprivate // expected-error {{duplicate modifier}}
func quadruplicateAttrChanged() {}
private(set)
public
var customSetter = 0
fileprivate(set)
public
var customSetter2 = 0
private(set) // expected-note {{modifier already specified here}}
public(set) // expected-error {{duplicate modifier}}
var customSetterDuplicateAttr = 0
private(set) // expected-note {{modifier already specified here}}
public // expected-note {{modifier already specified here}}
public(set) // expected-error {{duplicate modifier}}
private // expected-error {{duplicate modifier}}
var customSetterDuplicateAttrsAllAround = 0
private(get) // expected-error{{expected 'set' as subject of 'private' modifier}}
var invalidSubject = 0
private(42) // expected-error{{expected 'set' as subject of 'private' modifier}}
var invalidSubject2 = 0
private(a bunch of random tokens) // expected-error{{expected 'set' as subject of 'private' modifier}} expected-error{{expected declaration}}
var invalidSubject3 = 0
private(set // expected-error{{expected ')' in 'private' modifier}}
var unterminatedSubject = 0
private(42 // expected-error{{expected 'set' as subject of 'private' modifier}} expected-error{{expected declaration}}
var unterminatedInvalidSubject = 0
private() // expected-error{{expected 'set' as subject of 'private' modifier}}
var emptySubject = 0
private( // expected-error{{expected 'set' as subject of 'private' modifier}}
var unterminatedEmptySubject = 0
// Check that the parser made it here.
duplicateAttr(1) // expected-error{{argument passed to call that takes no arguments}}
// CHECK ALLOWED DECLS
private import Swift // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-9=}}
private(set) infix operator ~~~ // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-14=}}
private typealias MyInt = Int
private struct TestStruct {
private typealias LocalInt = MyInt
private var x = 0
private let y = 1
private func method() {}
private static func method() {}
private init() {}
private subscript(_: MyInt) -> LocalInt { return x }
}
private class TestClass {
private init() {}
internal deinit {} // expected-error {{'internal' modifier cannot be applied to this declaration}} {{3-12=}}
}
private enum TestEnum {
private case Foo, Bar // expected-error {{'private' modifier cannot be applied to this declaration}} {{3-11=}}
}
private protocol TestProtocol {
private associatedtype Foo // expected-error {{'private' modifier cannot be applied to this declaration}} {{3-11=}}
internal var Bar: Int { get } // expected-error {{'internal' modifier cannot be used in protocols}} {{3-12=}}
public func baz() // expected-error {{'public' modifier cannot be used in protocols}} {{3-10=}}
}
public(set) func publicSetFunc() {} // expected-error {{'public' modifier cannot be applied to this declaration}} {{1-13=}}
public(set) var defaultVis = 0 // expected-error {{internal variable cannot have a public setter}}
internal(set) private var privateVis = 0 // expected-error {{private variable cannot have an internal setter}}
private(set) var defaultVisOK = 0
private(set) public var publicVis = 0
private(set) var computed: Int { // expected-error {{'private(set)' modifier cannot be applied to read-only variables}} {{1-14=}}
return 42
}
private(set) var computedRW: Int {
get { return 42 }
set { }
}
private(set) let constant = 42 // expected-error {{'private(set)' modifier cannot be applied to constants}} {{1-14=}}
public struct Properties {
private(set) var stored = 42
private(set) var computed: Int { // expected-error {{'private(set)' modifier cannot be applied to read-only properties}} {{3-16=}}
return 42
}
private(set) var computedRW: Int {
get { return 42 }
set { }
}
private(set) let constant = 42 // expected-error {{'private(set)' modifier cannot be applied to read-only properties}} {{3-16=}}
public(set) var defaultVis = 0 // expected-error {{internal property cannot have a public setter}}
public(set) subscript(a a: Int) -> Int { // expected-error {{internal subscript cannot have a public setter}}
get { return 0 }
set {}
}
internal(set) private subscript(b b: Int) -> Int { // expected-error {{private subscript cannot have an internal setter}}
get { return 0 }
set {}
}
private(set) subscript(c c: Int) -> Int {
get { return 0 }
set {}
}
private(set) public subscript(d d: Int) -> Int {
get { return 0 }
set {}
}
private(set) subscript(e e: Int) -> Int { return 0 } // expected-error {{'private(set)' modifier cannot be applied to read-only subscripts}} {{3-16=}}
}
private extension Properties {
public(set) var extProp: Int { // expected-error {{private property cannot have a public setter}}
get { return 42 }
set { }
}
}
internal protocol EmptyProto {}
internal protocol EmptyProto2 {}
private extension Properties : EmptyProto {} // expected-error {{'private' modifier cannot be used with extensions that declare protocol conformances}} {{1-9=}}
private(set) extension Properties : EmptyProto2 {} // expected-error {{'private' modifier cannot be applied to this declaration}} {{1-14=}}
public struct PublicStruct {}
internal struct InternalStruct {} // expected-note * {{declared here}}
private struct PrivateStruct {} // expected-note * {{declared here}}
protocol InternalProto { // expected-note * {{declared here}}
associatedtype Assoc
}
public extension InternalProto {} // expected-error {{extension of internal protocol cannot be declared public}} {{1-8=}}
internal extension InternalProto where Assoc == PublicStruct {}
internal extension InternalProto where Assoc == InternalStruct {}
internal extension InternalProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared internal because its generic requirement uses a private type}}
private extension InternalProto where Assoc == PublicStruct {}
private extension InternalProto where Assoc == InternalStruct {}
private extension InternalProto where Assoc == PrivateStruct {}
public protocol PublicProto {
associatedtype Assoc
}
public extension PublicProto {}
public extension PublicProto where Assoc == PublicStruct {}
public extension PublicProto where Assoc == InternalStruct {} // expected-error {{extension cannot be declared public because its generic requirement uses an internal type}}
public extension PublicProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared public because its generic requirement uses a private type}}
internal extension PublicProto where Assoc == PublicStruct {}
internal extension PublicProto where Assoc == InternalStruct {}
internal extension PublicProto where Assoc == PrivateStruct {} // expected-error {{extension cannot be declared internal because its generic requirement uses a private type}}
private extension PublicProto where Assoc == PublicStruct {}
private extension PublicProto where Assoc == InternalStruct {}
private extension PublicProto where Assoc == PrivateStruct {}
extension PublicProto where Assoc == InternalStruct {
public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}}
}
extension InternalProto {
public func foo() {} // no effect, but no warning
}
extension InternalProto where Assoc == PublicStruct {
public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}}
}
public struct GenericStruct<Param> {}
public extension GenericStruct where Param: InternalProto {} // expected-error {{extension cannot be declared public because its generic requirement uses an internal type}}
extension GenericStruct where Param: InternalProto {
public func foo() {} // expected-error {{cannot declare a public instance method in an extension with internal requirements}} {{3-9=internal}}
}
public protocol ProtoWithReqs {
associatedtype Assoc
func foo()
}
public struct Adopter<T> : ProtoWithReqs {}
extension Adopter {
typealias Assoc = Int // expected-error {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{3-3=public }}
func foo() {} // expected-error {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{3-3=public }}
}
public class AnotherAdopterBase {
typealias Assoc = Int // expected-error {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{3-3=public }}
func foo() {} // expected-error {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{3-3=public }}
}
public class AnotherAdopterSub : AnotherAdopterBase, ProtoWithReqs {}
public protocol ReqProvider {}
extension ReqProvider {
func foo() {} // expected-error {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{3-3=public }}
}
public struct AdoptViaProtocol : ProtoWithReqs, ReqProvider {
public typealias Assoc = Int
}
public protocol ReqProvider2 {}
extension ProtoWithReqs where Self : ReqProvider2 {
func foo() {} // expected-error {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{3-3=public }}
}
public struct AdoptViaCombinedProtocol : ProtoWithReqs, ReqProvider2 {
public typealias Assoc = Int
}
|
apache-2.0
|
95363e1ca0dacfd4e7d5e20f6514cdf2
| 42.824034 | 176 | 0.73744 | 4.403191 | false | false | false | false |
soffes/X
|
Sources/X/Font.swift
|
1
|
1652
|
#if os(macOS)
import AppKit.NSFont
public typealias Font = NSFont
extension Font {
public var symbolicTraits: FontDescriptorSymbolicTraits {
return FontDescriptorSymbolicTraits(symbolicTraits: fontDescriptor.symbolicTraits.rawValue)
}
}
#else
import UIKit.UIFont
public typealias Font = UIFont
extension Font {
public var symbolicTraits: FontDescriptorSymbolicTraits {
return fontDescriptor.symbolicTraits
}
}
#endif
extension Font {
public var fontWithMonospacedNumbers: Font {
#if os(macOS)
let fontDescriptor = self.fontDescriptor.addingAttributes([
NSFontDescriptor.AttributeName.featureSettings: [
[
NSFontDescriptor.FeatureKey.typeIdentifier: kNumberSpacingType,
NSFontDescriptor.FeatureKey.selectorIdentifier: kMonospacedNumbersSelector
]
]
])
return Font(descriptor: fontDescriptor, size: pointSize) ?? self
#elseif os(watchOS)
let fontDescriptor = UIFontDescriptor(name: fontName, size: pointSize).addingAttributes([
UIFontDescriptor.AttributeName.featureSettings: [
[
UIFontDescriptor.FeatureKey.featureIdentifier: 6,
UIFontDescriptor.FeatureKey.typeIdentifier: 0
]
]
])
return Font(descriptor: fontDescriptor, size: pointSize)
#else
let fontDescriptor = UIFontDescriptor(name: fontName, size: pointSize).addingAttributes([
UIFontDescriptor.AttributeName.featureSettings: [
[
UIFontDescriptor.FeatureKey.featureIdentifier: kNumberSpacingType,
UIFontDescriptor.FeatureKey.typeIdentifier: kMonospacedNumbersSelector
]
]
])
return Font(descriptor: fontDescriptor, size: pointSize)
#endif
}
}
|
mit
|
4a680fad6802b17a3435dceece525b30
| 28.5 | 94 | 0.756053 | 4.464865 | false | false | false | false |
mitchtreece/Spider
|
Spider/Classes/Core/HTTP/HTTPStatusCode.swift
|
1
|
13934
|
//
// HTTPStatusCode.swift
// Spider-Web
//
// Created by Mitch Treece on 8/23/18.
//
import Foundation
// Source: https://httpstatuses.com
public extension HTTPStatusCode {
/// Flag indicating if the status code is considered `OK`.
///
/// A status code is considered `OK` if it's value is contained in the `200..<300` range.
var isOk: Bool {
return (200..<300).contains(self.rawValue)
}
/// Creates an `HTTPStatusCode` from a url response.
/// - Parameter response: The url response.
/// - Returns: An optional `HTTPStatusCode`.
static func from(response: URLResponse?) -> HTTPStatusCode? {
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
return HTTPStatusCode(rawValue: statusCode)
}
return nil
}
}
/// Representation of the various HTTP status codes.
public enum HTTPStatusCode: Int {
// MARK: 100's - Informational
/// The initial part of a request has been received and has not yet been rejected by the server.
/// The server intends to send a final response after the request has been fully received and acted upon.
case `continue` = 100
/// The server understands and is willing to comply with the client's request, via the `Upgrade` header field,
/// for a change in the application protocol being used on this connection.
case switchingProtocols = 101
/// An interim response used to inform the client that the server has accepted the complete request,
/// but has not yet completed it.
case processing = 102
// MARK: 200's - Success
/// The payload sent in a `200` response depends on the request method. Aside from responses to `CONNECT`,
/// a `200` response always has a payload, though an origin server _may_ generate a payload body of zero length.
/// If no payload is desired, an origin server ought to send `204 No Content` instead.
/// For `CONNECT`, no payload is allowed because the successful result is a tunnel,
/// which begins immediately after the `200` response header section.
case ok = 200
/// The request has been fulfilled and has resulted in one or more new resources being created.
case created = 201
/// The request has been accepted for processing, but the processing has not been completed.
/// The request might or might not eventually be acted upon, as it might be disallowed when processing actually takes place.
case accepted = 202
/// The request was successful but the enclosed payload has been modified from that of the origin server's
/// `200 OK` response by a transforming proxy.
case nonAuthoritativeInfo = 203
/// The server has successfully fulfilled the request and that there is no additional content to send in the response payload body.
case noContent = 204
/// The server has fulfilled the request and desires that the user agent reset the \"document view\",
/// which caused the request to be sent, to its original state as received from the origin server.
case resetContent = 205
/// The server is successfully fulfilling a range request for the target resource by transferring one or more
/// parts of the selected representation that correspond to the satisfiable ranges found in the request's Range header field.
case partialContent = 206
/// A Multi-Status response conveys information about multiple resources in situations where multiple
/// status codes might be appropriate.
case multiStatus = 207
/// Used inside a DAV: propstat response element to avoid enumerating the internal members of
/// multiple bindings to the same collection repeatedly.
case alreadyReported = 208
/// The server has fulfilled a `GET` request for the resource, and the response is a representation of the
/// result of one or more instance-manipulations applied to the current instance.
case imUsed = 226
// MARK: 300's - Redirection
/// The target resource has more than one representation, each with its own more specific identifier,
/// and information about the alternatives is being provided so that the user (or user agent)
/// can select a preferred representation by redirecting its request to one or more of those identifiers.
case multipleChoices = 300
/// The target resource has been assigned a new permanent URI and any future references to this
/// resource ought to use one of the enclosed URIs.
case movedPermanently = 301
/// The target resource resides temporarily under a different URI. Since the redirection might be altered on occasion,
/// the client ought to continue to use the effective request URI for future requests.
case found = 302
/// The server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field,
/// which is intended to provide an indirect response to the original request.
case seeOther = 303
/// A conditional `GET` or `HEAD` request has been received and would have resulted in a `200 OK` response
/// if it were not for the fact that the condition evaluated to false.
case notModified = 304
/// Defined in a previous version of this specification and is now deprecated,
/// due to security concerns regarding in-band configuration of a proxy.
case useProxy = 305
/// The target resource resides temporarily under a different URI and the user agent
/// **must not** change the request method if it performs an automatic redirection to that URI.
case temporaryRedirect = 307
/// The target resource has been assigned a new permanent URI and any future references
/// to this resource ought to use one of the enclosed URIs.
case permanentRedirect = 308
// MARK: 400's - Client error
/// The server cannot or will not process the request due to something that is perceived to be a client error
/// (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).
case badRequest = 400
/// The request has not been applied because it lacks valid authentication credentials for the target resource.
case unauthorized = 401
/// Reserved for future use.
case paymentRequired = 402
/// The server understood the request but refuses to authorize it.
case forbidden = 403
/// The origin server did not find a current representation for the target resource
/// or is not willing to disclose that one exists.
case notFound = 404
/// The method received in the request-line is known by the origin server but not supported by the target resource.
case methodNotAllowed = 405
/// The target resource does not have a current representation that would be acceptable to the user agent,
/// according to the proactive negotiation header fields received in the request,
/// and the server is unwilling to supply a default representation.
case notAcceptable = 406
/// Similar to `401 Unauthorized`, but it indicates that the client needs to authenticate itself in order to use a proxy.
case proxyAuthenticationRequired = 407
/// The server did not receive a complete request message within the time that it was prepared to wait.
case requestTimeout = 408
/// The request could not be completed due to a conflict with the current state of the target resource.
/// This code is used in situations where the user might be able to resolve the conflict and resubmit the request.
case conflict = 409
/// The target resource is no longer available at the origin server and that this condition is likely to be permanent.
case gone = 410
/// The server refuses to accept the request without a defined Content-Length.
case lengthRequired = 411
/// One or more conditions given in the request header fields evaluated to false when tested on the server.
case preconditionFailed = 412
/// The server is refusing to process a request because the request payload is
/// larger than the server is willing or able to process.
case payloadTooLarge = 413
/// The server is refusing to service the request because the request-target is
/// longer than the server is willing to interpret.
case requestURITooLong = 414
/// The origin server is refusing to service the request because the payload is in a
/// format not supported by this method on the target resource.
case unsupportedMediaType = 415
/// None of the ranges in the request's Range header field overlap the current extent of the
/// selected resource or that the set of ranges requested has been rejected due to
/// invalid ranges or an excessive request of small or overlapping ranges.
case requestedRangeNotSatisfiable = 416
/// The expectation given in the request's `Expect` header field could not be met by at least one of the inbound servers.
case expectationFailed = 417
/// Any attempt to brew coffee with a teapot should result in the error code
///`418 I'm a teapot`. The resulting entity body _may_ be short and stout.
case teapot = 418
/// The request was directed at a server that is not able to produce a response.
/// This can be sent by a server that is not configured to produce responses for the
/// combination of scheme and authority that are included in the request URI.
case misdirectedRequest = 421
/// The server understands the content type of the request entity
/// (hence a `415 Unsupported Media Type` status code is inappropriate), and the syntax of the
/// request entity is correct (thus a `400 Bad Request` status code is inappropriate) but was
/// unable to process the contained instructions.
case unprocessableEntity = 422
/// The source or destination resource of a method is locked.
case locked = 423
/// The method could not be performed on the resource because the requested
/// action depended on another action and that action failed.
case failedDependency = 424
/// The server refuses to perform the request using the current protocol but might be
/// willing to do so after the client upgrades to a different protocol.
case upgradeRequired = 426
/// The origin server requires the request to be conditional.
case preconditionRequired = 428
/// The user has sent too many requests in a given amount of time (\"rate limiting\").
case tooManyRequests = 429
/// The server is unwilling to process the request because its header fields are too large.
/// The request _may_ be resubmitted after reducing the size of the request header fields.
case requestHeaderFieldsTooLarge = 431
/// A non-standard status code used to instruct nginx to close the connection without
/// sending a response to the client, most commonly used to deny malicious or malformed requests.
case connectionClosedWithoutResponse = 444
/// The server is denying access to the resource as a consequence of a legal demand.
case unavailableForLegalReasons = 451
/// A non-standard status code introduced by nginx for the case when a client
/// closes the connection while nginx is processing the request.
case clientClosedRequest = 499
// MARK: 500's - Server error
/// The server encountered an unexpected condition that prevented it from fulfilling the request.
case internalServerError = 500
/// The server does not support the functionality required to fulfill the request.
case notImplemented = 501
/// The server, while acting as a gateway or proxy, received an invalid response from an
/// inbound server it accessed while attempting to fulfill the request.
case badGateway = 502
/// The server is currently unable to handle the request due to a temporary overload or scheduled maintenance,
/// which will likely be alleviated after some delay.
case serviceUnavailable = 503
/// The server, while acting as a gateway or proxy, did not receive a timely response from an
/// upstream server it needed to access in order to complete the request.
case gatewayTimeout = 504
/// The server does not support, or refuses to support, the major version of HTTP that was used in the request message.
case httpVersionNotSupported = 505
/// The server has an internal configuration error: the chosen variant resource is configured to engage in
/// transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
case variantAlsoNegotiates = 506
/// The method could not be performed on the resource because the server is unable to
/// store the representation needed to successfully complete the request.
case insufficientStorage = 507
/// The server terminated an operation because it encountered an infinite loop while
/// processing a request with \"Depth: infinity\". This status indicates that the entire operation failed.
case loopDetected = 508
/// The policy for accessing the resource has not been met in the request.
/// The server should send back all the information necessary for the client to issue an extended request.
case notExtended = 510
/// The client needs to authenticate to gain network access.
case networkAuthenticationRequired = 511
/// This status code is not specified in any RFCs, but is used by some HTTP proxies to signal a
/// network connect timeout behind the proxy to a client in front of the proxy.
case networkConnectTimeoutError = 599
}
|
mit
|
0f4eba460db1e88d58dad24389d7eb4c
| 47.048276 | 135 | 0.709201 | 5.181852 | false | false | false | false |
cconway/RFduinoUBP
|
iOS/UBP-Demo/UBP-Demo/SLIPBuffer.swift
|
1
|
2935
|
//
// SLIPBuffer.swift
// UBA-Demo
//
// Created by Chas Conway on 2/4/15.
// Copyright (c) 2015 Chas Conway. All rights reserved.
//
import Foundation
let PacketIdentifierLength = sizeof(UInt16)
let PacketFlagsLength = sizeof(UInt8)
let PacketChecksumLength = sizeof(UInt8)
protocol SLIPBufferDelegate {
func slipBufferReceivedPayload(payloadData:NSData, payloadIdentifier:UInt16, txFlags:UInt8)
}
class SLIPBuffer {
var rxBuffer = NSMutableData()
var delegate:SLIPBufferDelegate?
init() { // NOTE: Why is this required?
}
func appendEscapedBytes(escapedData:NSData) {
rxBuffer.appendData(escapedData)
scanRxBufferForFrames()
}
func scanRxBufferForFrames() {
let endByteIndices = rxBuffer.indexesOfEndBytes()
var previousIndex = NSNotFound
endByteIndices.enumerateIndexesUsingBlock { (anIndex, stop) -> Void in
if (previousIndex != NSNotFound) {
if anIndex - previousIndex > 2 { // Contains at least one byte and checksum byte
println("Identified a potential SLIP frame")
let escapedPacketData = self.rxBuffer.subdataWithRange(NSMakeRange(previousIndex + 1, anIndex - previousIndex - 1))
self.decodeSLIPPacket(escapedPacketData)
} else {
println("Ignoring improbable SLIP frame")
}
}
previousIndex = anIndex
}
// Remove byte in buffer up to, but not including, the last END byte
if previousIndex != NSNotFound {
self.rxBuffer.replaceBytesInRange(NSMakeRange(0, previousIndex), withBytes:UnsafePointer<Int8>.null(), length: 0)
}
}
func decodeSLIPPacket(escapedPacket:NSData) {
// Remove SLIP escaping
let unescapedPacket = escapedPacket.unescapedData()
// Extract embedded checksum from packet
var embeddedChecksumByte:Int8 = 0
unescapedPacket.getBytes(&embeddedChecksumByte, range: NSMakeRange(unescapedPacket.length - PacketChecksumLength, PacketChecksumLength))
// Calculate checksum on payload bytes
let checksummedData = unescapedPacket.subdataWithRange(NSMakeRange(0, unescapedPacket.length - PacketChecksumLength))
let calculatedChecksum = checksummedData.CRC8Checksum()
if calculatedChecksum == embeddedChecksumByte {
if let aDelegate = delegate {
// Extract payload and payload ID
var identifier:UInt16 = 0;
checksummedData.getBytes(&identifier, range: NSMakeRange(0, PacketIdentifierLength))
var txFlags:UInt8 = 0;
checksummedData.getBytes(&txFlags, range: NSMakeRange(PacketIdentifierLength - 1, PacketFlagsLength))
let payloadData = checksummedData.subdataWithRange(NSMakeRange(PacketIdentifierLength + PacketFlagsLength, checksummedData.length - PacketFlagsLength - PacketIdentifierLength))
// Notify delegate
aDelegate.slipBufferReceivedPayload(payloadData, payloadIdentifier:identifier, txFlags:txFlags)
}
} else {
println("SLIP frame failed checksum")
}
}
}
|
mit
|
76cfaa3062b46954f1361be8f4f69af4
| 27.230769 | 180 | 0.735264 | 4.037139 | false | false | false | false |
peferron/algo
|
EPI/Strings/Test palindromicity/swift/main.swift
|
1
|
1353
|
// swiftlint:disable variable_name
func isAlphanumeric(_ character: Character) -> Bool {
return "0" <= character && character <= "9" ||
"a" <= character && character <= "z" ||
"A" <= character && character <= "Z"
}
public func isPalindromeSimple(_ string: String) -> Bool {
let cleanedCharacters = string.lowercased().filter(isAlphanumeric)
return cleanedCharacters == String(cleanedCharacters.reversed())
}
public func isPalindromeSmart(_ string: String) -> Bool {
guard string != "" else {
return true
}
// Iterate from both ends of the string towards the center. Non-alphanumeric characters are
// skipped, and alphanumeric characters are compared case-insensitively.
var start = string.startIndex
var end = string.index(before: string.endIndex)
while true {
while start < end && !isAlphanumeric(string[start]) {
start = string.index(after: start)
}
while start < end && !isAlphanumeric(string[end]) {
end = string.index(before: end)
}
guard start < end else {
return true
}
guard String(string[start]).lowercased() == String(string[end]).lowercased() else {
return false
}
start = string.index(after: start)
end = string.index(before: end)
}
}
|
mit
|
f1ec3a5a84d4720ba5ed3783e1ff9af4
| 29.75 | 95 | 0.614191 | 4.392857 | false | false | false | false |
contentful/contentful.swift
|
Sources/Contentful/TypedQuery.swift
|
1
|
26089
|
//
// TypedQuery.swift
// Contentful
//
// Created by JP Wright on 12.10.17.
// Copyright © 2017 Contentful GmbH. All rights reserved.
//
import Foundation
/// A concrete implementation of ChainableQuery which can be used to make queries on `/entries/`
/// or `/entries`. All methods from ChainableQuery are available.
public class Query: ResourceQuery, EntryQuery {
public static var any: Query {
return Query()
}
}
/// An additional query to filter by the properties of linked objects when searching on references.
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references>
/// and see the init<LinkType: EntryDecodable>(whereLinkAt fieldNameForLink: String, matches filterQuery: FilterQuery<LinkType>? = nil) methods
/// on QueryOn for example usage.
public final class LinkQuery<EntryType>: AbstractQuery where EntryType: EntryDecodable & FieldKeysQueryable {
/// The parameters dictionary that are converted to `URLComponents` (HTTP parameters/arguments) on the HTTP URL. Useful for debugging.
public var parameters: [String: String] = [String: String]()
// Different function name to ensure inner call to where(valueAtKeyPath:operation:) doesn't recurse.
private static func with(valueAtKeyPath keyPath: String, _ operation: Query.Operation) -> LinkQuery<EntryType> {
let filterQuery = LinkQuery<EntryType>.where(valueAtKeyPath: keyPath, operation)
filterQuery.propertyName = keyPath
filterQuery.operation = operation
return filterQuery
}
/// Static method for creating a new LinkQuery with an operation. This variation for initializing guarantees
/// correct query contruction by utilizing the associated Fields CodingKeys type required by ResourceQueryable on the type you are linking to.
///
/// Example usage:
///
/// ```
/// let linkQuery = LinkQuery<Cat>.where(field: .name, .matches("Happy Cat"))
/// let query = QueryOn<Cat>(whereLinkAtField: .bestFriend, matches: linkQuery)
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references>
///
/// - Parameters:
/// - field: The member of the `FieldKeys` type associated with your type conforming to `EntryDecodable & ResourceQueryable`
/// that you are performing your search on reference against.
/// - operation: The query operation used in the query.
/// - Returns: A newly initialized `QueryOn` query.
public static func `where`(field: EntryType.FieldKeys, _ operation: Query.Operation) -> LinkQuery<EntryType> {
return LinkQuery<EntryType>.with(valueAtKeyPath: "fields.\(field.stringValue)", operation)
}
/**
Static method for creating a new LinkQuery with an operation. This variation for initializing guarantees
correct query contruction by utilizing the associated Sys CodingKeys type required by ResourceQueryable on
the type you are linking to.
Example usage:
```
let linkQuery = LinkQuery<Cat>.where(sys: .id, .matches("happycat"))
let query = QueryOn<Cat>(whereLinkAtField: .bestFriend, matches: linkQuery)
client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
switch result {
case .success(let arrayResponse):
let cats = arrayResponse.items
// Do stuff with cats.
case .failure(let error):
print(error)
}
}
```
See: [Search on references](https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references)
- Parameters:
- sys: The member of the `Sys.CodingKeys` type associated with your type conforming
to `EntryDecodable & ResourceQueryable` that you are performing your search on reference against.
- operation: The query operation used in the query.
- Returns: A newly initialized `QueryOn` query.
*/
public static func `where`(sys key: Sys.CodingKeys, _ operation: Query.Operation) -> LinkQuery<EntryType> {
return LinkQuery<EntryType>.with(valueAtKeyPath: "sys.\(key.stringValue)", operation)
}
/// Designated initializer for FilterQuery.
public init() {
self.parameters = [String: String]()
}
// MARK: FilterQuery<EntryType>.Private
fileprivate var operation: Query.Operation!
fileprivate var propertyName: String?
}
/// A concrete implementation of EntryQuery which requires that a model class conforming to `EntryType`
/// be passed in as a generic parameter.
/// The "content_type" parameter of the query will be set using the `contentTypeID` of the generic parameter conforming
/// to `EntryDecodable`. You must also implement `ResourceQueryable` in order to utilize these generic queries.
public final class QueryOn<EntryType>: EntryQuery where EntryType: EntryDecodable & FieldKeysQueryable {
/// The parameters dictionary that are converted to `URLComponents` (HTTP parameters/arguments) on the HTTP URL. Useful for debugging.
public var parameters: [String: String] = [String: String]()
/// Designated initializer for `QueryOn<EntryType>`.
public init() {
self.parameters = [QueryParameter.contentType: EntryType.contentTypeId]
}
/// Static method for creating a new `QueryOn` with an operation. This variation for initialization guarantees correct query construction
/// by utilizing the associated `FieldKeys` type required by `ResourceQueryable`.
///
/// Example usage:
///
/// ```
/// let query = QueryOn<Cat>.where(field: .color, .equals("gray"))
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters>
/// - Parameters:
/// - field: The member of the `FieldKeys` type associated with your type conforming to `EntryDecodable & ResourceQueryable`
/// that you are performing your select operation against.
/// - operation: The query operation used in the query.
/// - Returns: A newly initialized `QueryOn` query.
public static func `where`(field fieldsKey: EntryType.FieldKeys, _ operation: Query.Operation) -> QueryOn<EntryType> {
let query = QueryOn<EntryType>.where(valueAtKeyPath: "fields.\(fieldsKey.stringValue)", operation)
return query
}
/// Instance method for appending a query operation to the receiving `QueryOn`.
/// This variation for initialization guarantees correct query contruction by utilizing the associated
/// `FieldKeys` type required by `ResourceQueryable`.
///
/// Example usage:
///
/// ```
/// let query = QueryOn<Cat>().where(field: .color, .equals("gray"))
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters>
///
/// - Parameters:
/// - fieldsKey: The member of your `FieldKeys` type associated with your type conforming to `EntryDecodable & ResourceQueryable`
/// that you are performing your select operation against.
/// - operation: The query operation used in the query.
/// - Returns: A reference to the receiving query to enable chaining.
@discardableResult
public func `where`(field fieldsKey: EntryType.FieldKeys, _ operation: Query.Operation) -> QueryOn<EntryType> {
self.where(valueAtKeyPath: "fields.\(fieldsKey.stringValue)", operation)
return self
}
/// Static method for creating a new QueryOn with a select operation: an operation in which only
/// the fields specified in the fieldNames property will be returned in the JSON response. This variation for initializing guarantees correct query contruction
/// by utilizing the Fields CodingKeys required by ResourceQueryable.
/// The "sys" dictionary is always requested by the SDK.
/// Note that if you are using the select operator with an instance `QueryOn<EntryType>`
/// that your model types must have optional types for properties that you are omitting in the response (by not including them in your selections array).
/// If you are not using the `QueryOn` type while querying entries, make sure to specify the content type id.
/// Example usage:
///
/// ```
/// let query = QueryOn<Cat>.select(fieldsNamed: [.bestFriend, .color, .name])
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/select-operator>
///
/// - Parameter fieldsKeys: An array of `FieldKeys` associated with the genery `EntryType` that you are performing your select operation against.
/// - Returns: A newly initialized QueryOn query.
public static func select(fieldsNamed fieldsKeys: [EntryType.FieldKeys]) -> QueryOn<EntryType> {
let query = QueryOn<EntryType>()
query.select(fieldsNamed: fieldsKeys)
return query
}
/// Instance method for creating a new QueryOn with a select operation: an operation in which only
/// the fields specified in the fieldNames property will be returned in the JSON response. This variation for initializing guarantees correct query contruction
/// by utilizing the Fields type associated with your type conforming to ResourceQueryable.
/// The "sys" dictionary is always requested by the SDK.
/// Note that if you are using the select operator with an instance `QueryOn<EntryType>`
/// that your model types must have optional types for properties that you are omitting in the response (by not including them in your selections array).
/// If you are not using the `QueryOn` type while querying entries, make sure to specify the content type id.
///
/// Example usage:
///
/// ```
/// let query = QueryOn<Cat>().select(fieldsNamed: [.bestFriend, .color, .name])
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/select-operator>
///
/// - Parameter fieldsKeys: An array of `FieldKeys` associated with the genery `EntryType` that you are performing your select operation against.
/// - Returns: A reference to the receiving query to enable chaining.
@discardableResult
public func select(fieldsNamed fieldsKeys: [EntryType.FieldKeys]) -> QueryOn<EntryType> {
let fieldPaths = fieldsKeys.map { $0.stringValue }
try! self.select(fieldsNamed: fieldPaths)
return self
}
/// Static method for performing searches where linked entries or assets at the specified linking field match the filtering query.
/// For instance, if you want to query all entries of type "cat" where the "bestFriend" field links to cats with name matching "Happy Cat"
/// the code would look like the following:
///
/// ```
/// let linkQuery = LinkQuery<Cat>.where(field: .name, .matches("Happy Cat"))
/// let query = QueryOn<Cat>(whereLinkAtField: .bestFriend, matches: linkQuery)
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references>
///
/// - Parameters:
/// - fieldsKey: The `FieldKey` for the property which contains a link to another entry.
/// - linkQuery: The filter query applied to the linked objects which are being searched.
/// - Returns: A newly initialized `QueryOn` query.
public static func `where`<LinkType>(linkAtField fieldsKey: EntryType.FieldKeys,
matches linkQuery: LinkQuery<LinkType>) -> QueryOn<EntryType> {
let query = QueryOn<EntryType>()
query.where(linkAtField: fieldsKey, matches: linkQuery)
return query
}
/// Instance method for for performing searches where Linked objects at the specified linking field match the filtering query.
/// For instance, if you want to query all entries of type "cat" where the "bestFriend" field links to cats with name matching "Happy Cat"
/// the code would look like the following:
///
/// ```
/// let linkQuery = LinkQuery<Cat>.where(field: .name, .matches("Happy Cat"))
/// let query = QueryOn<Cat>(whereLinkAtField: .bestFriend, matches: linkQuery)///
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references>
///
/// - Parameters:
/// - fieldsKey: The `FieldKey` for the property which contains a link to another entry or asset.
/// - linkQuery: The filter query applied to the linked objects which are being searched.
/// - Returns: A reference to the receiving query to enable chaining.
@discardableResult
public func `where`<LinkType>(linkAtField fieldsKey: EntryType.FieldKeys,
matches linkQuery: LinkQuery<LinkType>) -> QueryOn<EntryType> {
parameters["fields.\(fieldsKey.stringValue).sys.contentType.sys.id"] = LinkType.contentTypeId
// If propertyName isn't unrwrapped, the string isn't constructed correctly for some reason.
if let propertyName = linkQuery.propertyName {
let filterParameterName = "fields.\(fieldsKey.stringValue).\(propertyName)\(linkQuery.operation.string)"
parameters[filterParameterName] = linkQuery.operation.values
}
return self
}
/// Static method fore creating a query requiring that a specific field of an entry
/// contains a reference to another specific entry.
///
/// ```
/// let query = QueryOn<Cat>(whereLinkAtField: .bestFriend, hasTargetId: "nyancat")
///
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references>
///
/// - Parameters:
/// - fieldsKey: The `FieldKey` of the property which contains a link to another Entry.
/// - targetId: The identifier of the entry or asset being linked to at the specified linking field.
/// - Returns: A newly initialized `QueryOn` query.
public static func `where`(linkAtField fieldsKey: EntryType.FieldKeys,
hasTargetId targetId: String) -> QueryOn<EntryType> {
let query = QueryOn<EntryType>()
query.where(linkAtField: fieldsKey, hasTargetId: targetId)
return query
}
/// Instance method creating a query that requires that an specific field of an entry
/// holds a reference to another specific entry.
///
/// ```
/// let query = QueryOn<Cat>(whereLinkAtField: .bestFriend, hasTargetId: "nyancat")
///
/// client.fetchArray(of: Cat.self, matching: query) { (result: Result<ArrayResponse<Cat>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let cats = arrayResponse.items
/// // Do stuff with cats.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/search-on-references>
///
/// - Parameters:
/// - fieldsKey: The `FieldKey` of the property which contains a link to another Entry.
/// - targetId: The identifier of the entry or asset being linked to at the specified linking field.
/// - Returns: A reference to the receiving query to enable chaining.
@discardableResult
public func `where`(linkAtField fieldsKey: EntryType.FieldKeys,
hasTargetId targetId: String) -> QueryOn<EntryType> {
let filterParameterName = "fields.\(fieldsKey.stringValue).sys.id"
parameters[filterParameterName] = targetId
return self
}
}
/// Queries on Asset types. All methods from `ChainableQuery` are available.
public final class AssetQuery: ResourceQuery {
/// Convenience initializer for creating an `AssetQuery` with the "mimetype_group" parameter specified. Example usage:
///
/// ```
/// let query = AssetQuery.where(mimetypeGroup: .image)
/// ```
///
/// - Parameter mimetypeGroup: The `mimetype_group` which all returned Assets will match.
/// - Returns: A newly initialized `AssetQuery` query.
public static func `where`(mimetypeGroup: MimetypeGroup) -> AssetQuery {
let query = AssetQuery()
query.where(mimetypeGroup: mimetypeGroup)
return query
}
/// Instance method for mutating the query further to specify the mimetype group when querying assets.
///
/// - Parameter mimetypeGroup: The `mimetype_group` which all returned Assets will match.
/// - Returns: A reference to the receiving query to enable chaining.
@discardableResult
public func `where`(mimetypeGroup: MimetypeGroup) -> AssetQuery {
self.parameters[QueryParameter.mimetypeGroup] = mimetypeGroup.rawValue
return self
}
/// Static method for creating a new `AssetQuery` with a select operation: an operation in which only
/// the fields specified in the fieldNames parameter will be returned in the JSON response.
/// This variation for initialization guarantees correct query contruction by utilizing the typesafe `Asset.FieldKeys`.
/// The "sys" dictionary is always requested by the SDK.
///
/// Example usage:
///
/// ```
/// let query = AssetQuery.select(fieldsNamed: [.file])
/// client.fetchArray(of: Asset.self, matching: query) { (result: Result<ArrayResponse<Asset>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let assets = arrayResponse.items
/// // Do stuff with assets.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/select-operator>
///
/// - Parameter fieldsKeys: An array of `Asset.FieldKeys` of the asset you are performing your select operation against.
/// - Returns: A newly initialized `AssetQuery` query.
public static func select(fields fieldsKeys: [Asset.Fields]) -> AssetQuery {
let query = AssetQuery()
query.select(fields: fieldsKeys)
return query
}
/// Instance method for mutating an `AssetQuery` with a select operation: an operation in which only
/// the fields specified in the fieldNames parameter will be returned in the JSON response.
/// This variation for initialization guarantees correct query contruction by utilizing the typesafe `Asset.FieldKeys`.
/// The "sys" dictionary is always requested by the SDK.
///
/// ```
/// let query = AssetQuery.select(fieldsNamed: [.file])
/// client.fetchMappedEntries(with: query).then { catsResponse in
/// let cats = catsResponse.items
/// // Do stuff with cats.
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters/select-operator>
///
/// - Parameter fieldsKeys: An array of `Asset.FieldKeys` of the asset you are performing your select operation against.
/// - Returns: A reference to the receiving query to enable chaining.
@discardableResult
public func select(fields fieldsKeys: [Asset.Fields]) -> AssetQuery {
let fieldPaths = fieldsKeys.map { $0.stringValue }
// Because we're guaranteed the keyPath doesn't have a "." in it, we can force try
try! self.select(fieldsNamed: fieldPaths)
return self
}
}
/// Queries on content types. All methods from ChainableQuery are available, are inherited and available.
public final class ContentTypeQuery: ChainableQuery {
/// The parameters dictionary that is converted to `URLComponents` (HTTP parameters/arguments) on the HTTP URL. Useful for debugging.
public var parameters: [String: String] = [String: String]()
/// Designated initalizer for Query.
public required init() {
self.parameters = [String: String]()
}
/// Static method for creating a ContentTypeQuery with an operation.
/// This variation for initializing guarantees correct query contruction by utilizing the ContentType.QueryableCodingKey CodingKeys.
///
/// Example usage:
///
/// ```
/// let query = ContentTypeQuery.where(queryableCodingKey: .name, .equals("Cat"))
/// client.fetchArray(of: ContentType.self, matching: query) { (result: Result<ArrayResponse<ContentType>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let contentTypes = arrayResponse.items
/// // Do stuff with contentTypes.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
///
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters>
///
/// - Parameters:
/// - queryableCodingKey: The member of your `ContentType.QueryableCodingKey` that you are performing your operation against.
/// - operation: The query operation used in the query.
/// - Returns: A newly initialized `AssetQuery` query.
public static func `where`(queryableCodingKey: ContentType.QueryableCodingKey, _ operation: Query.Operation) -> ContentTypeQuery {
let query = ContentTypeQuery()
query.where(valueAtKeyPath: "\(queryableCodingKey.stringValue)", operation)
return query
}
/// Instance method for appending a query operation to the receiving ContentTypeQuery.
/// This variation for initializing guarantees correct query construction by utilizing the ContentType.QueryableCodingKey CodingKeys.
///
/// Example usage:
///
/// ```
/// let query = ContentTypeQuery().where(queryableCodingKey: .name, .equals("Cat"))
/// client.fetchArray(of: ContentType.self, matching: query) { (result: Result<ArrayResponse<ContentType>>) in
/// switch result {
/// case .success(let arrayResponse):
/// let contentTypes = arrayResponse.items
/// // Do stuff with contentTypes.
/// case .failure(let error):
/// print(error)
/// }
/// }
/// ```
/// See: <https://www.contentful.com/developers/docs/references/content-delivery-api/#/reference/search-parameters>
///
/// - Parameters:
/// - queryableCodingKey: The member of your `ContentType.QueryableCodingKey` that you are performing your operation against.
/// - operation: The query operation used in the query.
/// - Returns: A reference to the receiving query to enable chaining.
@discardableResult
public func `where`(queryableCodingKey: ContentType.QueryableCodingKey, _ operation: Query.Operation) -> ContentTypeQuery {
self.where(valueAtKeyPath: "\(queryableCodingKey.stringValue)", operation)
return self
}
}
|
mit
|
fb7324dfee528e13601618523bddbece
| 47.762617 | 163 | 0.659 | 4.449599 | false | false | false | false |
bitjammer/swift
|
test/SILGen/address_only_types.swift
|
1
|
9186
|
// RUN: %target-swift-frontend -parse-as-library -parse-stdlib -emit-silgen %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
typealias Int = Builtin.Int64
enum Bool { case true_, false_ }
protocol Unloadable {
func foo() -> Int
var address_only_prop : Unloadable { get }
var loadable_prop : Int { get }
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B9_argument{{[_0-9a-zA-Z]*}}F
func address_only_argument(_ x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[XARG]]
// CHECK-NEXT: destroy_addr [[XARG]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B17_ignored_argument{{[_0-9a-zA-Z]*}}F
func address_only_ignored_argument(_: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: destroy_addr [[XARG]]
// CHECK-NOT: dealloc_stack {{.*}} [[XARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_return{{[_0-9a-zA-Z]*}}F
func address_only_return(_ x: Unloadable, y: Int) -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable, [[XARG:%[0-9]+]] : $*Unloadable, [[YARG:%[0-9]+]] : $Builtin.Int64):
// CHECK-NEXT: debug_value_addr [[XARG]] : $*Unloadable, let, name "x"
// CHECK-NEXT: debug_value [[YARG]] : $Builtin.Int64, let, name "y"
// CHECK-NEXT: copy_addr [[XARG]] to [initialization] [[RET]]
// CHECK-NEXT: destroy_addr [[XARG]]
// CHECK-NEXT: [[VOID:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[VOID]]
return x
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B15_missing_return{{[_0-9a-zA-Z]*}}F
func address_only_missing_return() -> Unloadable {
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B27_conditional_missing_return{{[_0-9a-zA-Z]*}}F
func address_only_conditional_missing_return(_ x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE:bb[0-9]+]]
switch Bool.true_ {
case .true_:
// CHECK: [[TRUE]]:
// CHECK: copy_addr %1 to [initialization] %0 : $*Unloadable
// CHECK: destroy_addr %1
// CHECK: return
return x
case .false_:
()
}
// CHECK: [[FALSE]]:
// CHECK: unreachable
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B29_conditional_missing_return_2
func address_only_conditional_missing_return_2(_ x: Unloadable) -> Unloadable {
// CHECK: bb0({{%.*}} : $*Unloadable, {{%.*}} : $*Unloadable):
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE1:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE1:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE1]]:
// CHECK: switch_enum {{%.*}}, case #Bool.true_!enumelt: [[TRUE2:bb[0-9]+]], case #Bool.false_!enumelt: [[FALSE2:bb[0-9]+]]
switch Bool.true_ {
case .true_:
return x
case .false_:
()
}
// CHECK: [[FALSE2]]:
// CHECK: unreachable
// CHECK: bb{{.*}}:
// CHECK: return
}
var crap : Unloadable = some_address_only_function_1()
func some_address_only_function_1() -> Unloadable { return crap }
func some_address_only_function_2(_ x: Unloadable) -> () {}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_call_1
func address_only_call_1() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable):
return some_address_only_function_1()
// FIXME emit into
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1AA10Unloadable_pyF
// CHECK: apply [[FUNC]]([[RET]])
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B21_call_1_ignore_returnyyF
func address_only_call_1_ignore_return() {
// CHECK: bb0:
some_address_only_function_1()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1AA10Unloadable_pyF
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B7_call_2{{[_0-9a-zA-Z]*}}F
func address_only_call_2(_ x: Unloadable) {
// CHECK: bb0([[XARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[XARG]] : $*Unloadable
some_address_only_function_2(x)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F
// CHECK: [[X_CALL_ARG:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[XARG]] to [initialization] [[X_CALL_ARG]]
// CHECK: apply [[FUNC]]([[X_CALL_ARG]])
// CHECK: dealloc_stack [[X_CALL_ARG]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B12_call_1_in_2{{[_0-9a-zA-Z]*}}F
func address_only_call_1_in_2() {
// CHECK: bb0:
some_address_only_function_2(some_address_only_function_1())
// CHECK: [[FUNC2:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_2{{[_0-9a-zA-Z]*}}F
// CHECK: [[FUNC1:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC1]]([[TEMP]])
// CHECK: apply [[FUNC2]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B12_materialize{{[_0-9a-zA-Z]*}}F
func address_only_materialize() -> Int {
// CHECK: bb0:
return some_address_only_function_1().foo()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_T018address_only_types05some_a1_B11_function_1{{[_0-9a-zA-Z]*}}F
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: apply [[FUNC]]([[TEMP]])
// CHECK: [[TEMP_PROJ:%[0-9]+]] = open_existential_addr immutable_access [[TEMP]] : $*Unloadable to $*[[OPENED:@opened(.*) Unloadable]]
// CHECK: [[FOO_METHOD:%[0-9]+]] = witness_method $[[OPENED]], #Unloadable.foo!1
// CHECK: [[RET:%[0-9]+]] = apply [[FOO_METHOD]]<[[OPENED]]>([[TEMP_PROJ]])
// CHECK: destroy_addr [[TEMP_PROJ]]
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B21_assignment_from_temp{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_temp(_ dest: inout Unloadable) {
// CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable):
dest = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [take] [[TEMP]] to %0 :
// CHECK-NOT: destroy_addr [[TEMP]]
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B19_assignment_from_lv{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_lv(_ dest: inout Unloadable, v: Unloadable) {
var v = v
// CHECK: bb0([[DEST:%[0-9]+]] : $*Unloadable, [[VARG:%[0-9]+]] : $*Unloadable):
// CHECK: [[VBOX:%.*]] = alloc_box ${ var Unloadable }
// CHECK: [[PBOX:%[0-9]+]] = project_box [[VBOX]]
// CHECK: copy_addr [[VARG]] to [initialization] [[PBOX]] : $*Unloadable
dest = v
// FIXME: emit into?
// CHECK: copy_addr [[PBOX]] to %0 :
// CHECK: destroy_value [[VBOX]]
}
var global_prop : Unloadable {
get {
return crap
}
set {}
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B33_assignment_from_temp_to_property{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_temp_to_property() {
// CHECK: bb0:
global_prop = some_address_only_function_1()
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_T018address_only_types11global_propAA10Unloadable_pfs
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B31_assignment_from_lv_to_property{{[_0-9a-zA-Z]*}}F
func address_only_assignment_from_lv_to_property(_ v: Unloadable) {
// CHECK: bb0([[VARG:%[0-9]+]] : $*Unloadable):
// CHECK: debug_value_addr [[VARG]] : $*Unloadable
// CHECK: [[TEMP:%[0-9]+]] = alloc_stack $Unloadable
// CHECK: copy_addr [[VARG]] to [initialization] [[TEMP]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_T018address_only_types11global_propAA10Unloadable_pfs
// CHECK: apply [[SETTER]]([[TEMP]])
// CHECK: dealloc_stack [[TEMP]]
global_prop = v
}
// CHECK-LABEL: sil hidden @_T018address_only_types0a1_B4_varAA10Unloadable_pyF
func address_only_var() -> Unloadable {
// CHECK: bb0([[RET:%[0-9]+]] : $*Unloadable):
var x = some_address_only_function_1()
// CHECK: [[XBOX:%[0-9]+]] = alloc_box ${ var Unloadable }
// CHECK: [[XPB:%.*]] = project_box [[XBOX]]
// CHECK: apply {{%.*}}([[XPB]])
return x
// CHECK: copy_addr [[XPB]] to [initialization] [[RET]]
// CHECK: destroy_value [[XBOX]]
// CHECK: return
}
func unloadable_to_unloadable(_ x: Unloadable) -> Unloadable { return x }
var some_address_only_nontuple_arg_function : (Unloadable) -> Unloadable = unloadable_to_unloadable
// CHECK-LABEL: sil hidden @_T018address_only_types05call_a1_B22_nontuple_arg_function{{[_0-9a-zA-Z]*}}F
func call_address_only_nontuple_arg_function(_ x: Unloadable) {
some_address_only_nontuple_arg_function(x)
}
|
apache-2.0
|
e8b70aabe07563eb3846916de9f9c4f2
| 38.93913 | 137 | 0.626061 | 2.927342 | false | false | false | false |
CoderLiLe/Swift
|
继承/main.swift
|
1
|
6772
|
//
// main.swift
// 继承
//
// Created by LiLe on 15/4/4.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
继承语法
继承是面向对象最显著的一个特性, 继承是从已经有的类中派生出新的类
新的类能够继承已有类的属性和方法, 并能扩展新的能力
术语: 基类(父类, 超类), 派生类(子类, 继承类)
语法:
class 子类: 父类{
}
继承有点: 代码重用
继承缺点: 增加程序耦合度, 父类改变会影响子类
注意:Swift和OC一样没有多继承
*/
class Man {
var name:String = "lnj"
var age: Int = 30
func sleep(){
print("睡觉")
}
}
class SuperMan: Man {
var power:Int = 100
func fly(){
// 子类可以继承父类的属性
print("飞 \(name) \(age)")
}
}
var m = Man()
m.sleep()
//m.fly() // 父类不可以使用子类的方法
var sm = SuperMan()
sm.sleep()// 子类可以继承父类的方法
sm.fly()
/*
super关键字:
派生类中可以通过super关键字来引用父类的属性和方法
*/
class Man2 {
var name:String = "lnj"
var age: Int = 30
func sleep(){
print("睡觉")
}
}
class SuperMan2: Man2 {
var power:Int = 100
func eat()
{
print("吃饭")
}
func fly(){
// 子类可以继承父类的属性
print("飞 \(super.name) \(super.age)")
}
func eatAndSleep()
{
eat()
super.sleep()
// 如果没有写super, 那么会现在当前类中查找, 如果找不到再去父类中查找
// 如果写了super, 会直接去父类中查找
}
}
var sm2 = SuperMan2()
sm2.eatAndSleep()
/*
方法重写: override
重写父类方法, 必须加上override关键字
*/
class Man3 {
var name:String = "lnj"
var age: Int = 30
func sleep(){
print("睡觉")
}
}
class SuperMan3: Man3 {
var power:Int = 100
// override关键字主要是为了明确表示重写父类方法,
// 所以如果要重写父类方法, 必须加上override关键字
override func sleep() {
// sleep() // 不能这样写, 会导致递归
super.sleep()
print("子类睡觉")
}
func eat()
{
print("吃饭")
}
func fly(){
// 子类可以继承父类的属性
print("飞 \(super.name) \(super.age)")
}
func eatAndSleep()
{
eat()
sleep()
}
}
var sm3 = SuperMan3()
// 通过子类调用, 优先调用子类重写的方法
//sm3.sleep()
sm3.eatAndSleep()
/*
重写属性
无论是存储属性还是计算属性, 都只能重写为计算属性
*/
class Man4 {
var name:String = "lnj" // 存储属性
var age: Int { // 计算属性
get{
return 30
}
set{
print("man new age \(newValue)")
}
}
func sleep(){
print("睡觉")
}
}
class SuperMan4: Man4 {
var power:Int = 100
// 可以将父类的存储属性重写为计算属性
// 但不可以将父类的存储属性又重写为存储属性, 因为这样没有意义
// override var name:String = "zs"
override var name:String{
get{
return "zs"
}
set{
print("SuperMan new name \(newValue)")
}
}
// 可以将父类的计算属性重写为计算属性, 同样不能重写为存储属性
override var age: Int { // 计算属性
get{
return 30
}
set{
print("superMan new age \(newValue)")
}
}
}
let sm4 = SuperMan4()
// 通过子类对象来调用重写的属性或者方法, 肯定会调用子类中重写的版本
sm4.name = "xxx"
sm4.age = 50
/*
重写属性的限制
1.读写计算属性/存储属性, 是否可以重写为只读计算属性? (权限变小)不可以
2.只读计算属性, 是否可以在重写时变成读写计算属性? (权限变大)可以
3.只需
*/
class Man5 {
var name:String = "lnj" // 存储属性
var age: Int { // 计算属性
get{
return 30
}
set{
print("man new age \(newValue)")
}
}
func sleep(){
print("睡觉")
}
}
class SuperMan5: Man5 {
var power:Int = 100
override var name:String{
get{
return "zs"
}
set{
print("SuperMan new name \(newValue)")
}
}
override var age: Int { // 计算属性
get{
return 30
}
set{
print("superMan new age \(newValue)")
}
}
}
/*
重写属性观察器
只能给非lazy属性的变量存储属性设定属性观察器,
不能给计算属性设置属性观察器,给计算属性设置属性观察器没有意义
属性观察器限制:
1.不能在子类中重写父类只读的存储属性
2.不能给lazy的属性设置属性观察器
*/
class Man6 {
var name: String = "lnj"
var age: Int = 0 { // 存储属性
willSet{
print("super new \(newValue)")
}
didSet{
print("super new \(oldValue)")
}
}
var height:Double{
get{
print("super get")
return 10.0
}
set{
print("super set")
}
}
}
class SuperMan6: Man6 {
// 可以在子类中重写父类的存储属性为属性观察器
override var name: String {
willSet{
print("new \(newValue)")
}
didSet{
print("old \(oldValue)")
}
}
// 可以在子类中重写父类的属性观察器
override var age: Int{
willSet{
print("child new \(newValue)")
}
didSet{
print("child old \(oldValue)")
}
}
// 可以在子类重写父类的计算属性为属性观察器
override var height:Double{
willSet{
print("child height")
}
didSet{
print("child height")
}
}
}
var m6 = SuperMan6()
//m6.age = 55
//print(m.age)
m6.height = 20.0
/*
利用final关键字防止重写
final关键字既可以修饰属性, 也可以修饰方法, 并且还可以修饰类
被final关键字修饰的属性和方法不能被重写
被final关键字修饰的类不能被继承
*/
final class Man7 {
final var name: String = "lnj"
final var age: Int = 0 { // 存储属性
willSet{
print("super new \(newValue)")
}
didSet{
print("super new \(oldValue)")
}
}
final var height:Double{
get{
print("super get")
return 10.0
}
set{
print("super set")
}
}
final func eat(){
print("吃饭")
}
}
|
mit
|
6f1cad85a1e3eb298ec455379b81570c
| 15.57508 | 50 | 0.507325 | 3.042815 | false | false | false | false |
zendobk/SwiftUtils
|
Sources/Extensions/Float.swift
|
1
|
1454
|
//
// Float.swift
// SwiftUtils
//
// Created by DaoNV on 10/7/15.
// Copyright © 2016 Asian Tech Co., Ltd. All rights reserved.
//
import Foundation
extension Float {
public var abs: Float {
return Foundation.fabsf(self)
}
public var sqrt: Float {
return Foundation.sqrt(self)
}
public var floor: Float {
return Foundation.floor(self)
}
public var ceil: Float {
return Foundation.ceil(self)
}
public var round: Float {
return Foundation.round(self)
}
public func clamp(_ min: Float, _ max: Float) -> Float {
return Swift.max(min, Swift.min(max, self))
}
public 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
}
public func distance(_ precision: Int = -1) -> String { // precision < 0: Auto
var num = self
var unit = "m"
if num > 1000.0 {
unit = "km"
num /= 1000.0
}
if precision == -1 {
if num == truncf(num) {
return String(format: "%.0f%@", num, unit)
} else {
return String(format: "%.1f%@", num, unit)
}
} else {
let format = "%.\(precision)f%@"
return String(format: format, num, unit)
}
}
}
|
apache-2.0
|
3bb1b91b8bf7cb813e1af8e463da3c28
| 23.216667 | 82 | 0.516173 | 3.813648 | false | false | false | false |
xhjkl/rayban
|
Rayban/MainView.swift
|
1
|
7524
|
//
// Overlay window main view
// which watches sources for changes,
// offers to select a new watching target
// and tells its subordinate Render View to recompile
// when needed
//
import Cocoa
class MainViewController: NSViewController {
lazy var openPanel: NSOpenPanel = {
let panel = NSOpenPanel()
panel.canChooseFiles = true
panel.canChooseDirectories = false
panel.allowsMultipleSelection = false
return panel
}()
lazy var detailsCallout: NSPopover = {
let callout = NSPopover()
callout.behavior = .transient
callout.contentViewController = self.detailsViewController
return callout
}()
lazy var detailsViewController: NSViewController = (
self.storyboard!.instantiateController(withIdentifier: "DetailsViewController")
) as! NSViewController
@IBOutlet weak var currentShaderField: NSTextField!
@IBOutlet weak var bottomStack: NSStackView!
@IBOutlet weak var renderView: RenderView!
private var filewatch = Filewatch()
private var targetPath = "" {
didSet {
targetFilenameDidChange(path: targetPath)
targetFileContentDidChange()
}
}
override func viewDidLoad() {
super.viewDidLoad()
renderView!.logListener = self
filewatch.addHandler { [weak self] in
self?.targetFileContentDidChange()
}
openPanel.orderFront(self)
let result = openPanel.runModal()
if result != NSFileHandlingPanelOKButton {
NSApp.terminate(self)
}
openPanel.close()
let path = openPanel.urls.first!.path
targetPath = path
filewatch.setTarget(path: targetPath)
}
private func targetFilenameDidChange(path: String) {
// Chop the home part
guard let home = ProcessInfo.processInfo.environment["HOME"] else {
// No home -- no chopping
currentShaderField.stringValue = path
return
}
var prettyPath = path
if prettyPath.hasPrefix(home) {
let afterHome = prettyPath.characters.index(prettyPath.startIndex, offsetBy: home.characters.count)
let pathAfterTilde = path.substring(from: afterHome)
prettyPath = "~"
if !pathAfterTilde.hasPrefix("/") {
prettyPath.append("/" as Character)
}
prettyPath.append(pathAfterTilde)
}
currentShaderField.stringValue = prettyPath
}
private func targetFileContentDidChange() {
let targetURL = URL(fileURLWithPath: targetPath)
// FS API could be slippery at times
var data = try? Data(contentsOf: targetURL)
if data == nil {
data = try? Data(contentsOf: targetURL)
if data == nil {
do {
data = try Data(contentsOf: targetURL)
} catch(let error) {
filewatch.setTarget(path: targetPath)
complainAboutFS(error: error, filewatch: filewatch.working)
}
}
}
guard data != nil else {
return
}
guard let source = String(data: data!, encoding: .utf8) else {
return
}
clearMessages()
renderView!.setSource(source)
// Reset the filewatch for the case when the editor writes by and moves over
filewatch.setTarget(path: targetPath)
if !filewatch.working {
complainAboutFilewatch()
}
}
@IBAction func moreButtonHasBeenClicked(_ sender: NSButton) {
self.detailsCallout.show(relativeTo: sender.frame, of: sender.superview!, preferredEdge: .minX)
}
@IBAction func currentShaderFieldHasBeenClicked(_ sender: AnyObject) {
openPanel.orderFront(self)
openPanel.begin(completionHandler: { [unowned self] status in
self.openPanel.orderOut(self)
if status != NSFileHandlingPanelOKButton {
return
}
let path = self.openPanel.urls.first!.path
self.targetPath = path
})
}
@IBAction func quitButtonHasBeenClicked(_ sender: AnyObject) {
NSApp.terminate(sender);
}
func clearMessages() {
DispatchQueue.main.async { [unowned self] in
self.bottomStack.arrangedSubviews.forEach { $0.removeFromSuperview() }
self.view.superview?.needsDisplay = true
}
}
func addMessage(severity: RenderLogMessageSeverity, header: String, body: String) {
DispatchQueue.main.async { [unowned self] in
self.bottomStack.addArrangedSubview(self.makeReportView(severity, header, body))
self.view.superview?.needsDisplay = true
}
}
private func complainAboutFS(error: Error, filewatch working: Bool) {
NSLog("run-time expectation violated:\n"
+ "detected change in target file; however could not read it: \n\(error)\n"
+ "continuing to watch the same file")
if !working {
NSLog("moreover, file watch mechanism could not open the file for reading; suspending")
}
}
private func complainAboutFilewatch() {
NSLog("could not attach watcher to the target file; try picking the file again")
}
private func makeReportView(_ severity: RenderLogMessageSeverity, _ header: String, _ message: String) -> NSView {
var bulletColor: NSColor! = nil
switch severity {
case .unknown:
bulletColor = NSColor(calibratedHue: 0.86, saturation: 0.9, brightness: 0.9, alpha: 1.0)
case .warning:
bulletColor = NSColor(calibratedHue: 0.14, saturation: 0.9, brightness: 0.9, alpha: 1.0)
case .error:
bulletColor = NSColor(calibratedHue: 0.01, saturation: 0.9, brightness: 0.9, alpha: 1.0)
}
let fontSize = NSFont.systemFontSize()
let sigilView = NSTextField()
sigilView.isEditable = false
sigilView.isSelectable = false
sigilView.isBordered = false
sigilView.drawsBackground = false
sigilView.font = NSFont.monospacedDigitSystemFont(ofSize: 1.4 * fontSize, weight: 1.0)
sigilView.textColor = bulletColor
sigilView.stringValue = "•"
sigilView.sizeToFit()
let headerView = NSTextField()
headerView.isEditable = false
headerView.isSelectable = false
headerView.isBordered = false
headerView.drawsBackground = false
headerView.font = NSFont.monospacedDigitSystemFont(ofSize: fontSize, weight: 1.0)
headerView.textColor = .white
headerView.stringValue = header
headerView.sizeToFit()
let messageView = NSTextField()
messageView.isEditable = false
messageView.isSelectable = true
messageView.isBordered = false
messageView.drawsBackground = false
messageView.font = NSFont.systemFont(ofSize: fontSize, weight: 0.1)
messageView.textColor = .white
messageView.stringValue = message
messageView.sizeToFit()
let container = NSStackView(views: [sigilView, headerView, messageView])
container.orientation = .horizontal
container.alignment = .firstBaseline
return container
}
}
extension MainViewController: RenderLogListener {
func onReport(_ message: RenderLogMessage) {
let (severity, row, column, body) = message
var header = ""
if let row = row, let column = column {
header = "\(row):\(column): "
}
addMessage(severity: severity, header: header, body: body)
}
}
class MainView: NSView {
let borderRadius = CGFloat(8)
let backgroundColor = NSColor(deviceRed: 0.0, green: 0.0, blue: 0.0, alpha: 0.7)
override init(frame: NSRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
super.init(coder: coder)
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
let roundedRect = NSBezierPath(
roundedRect: self.frame,
xRadius: self.borderRadius,
yRadius: self.borderRadius
)
self.backgroundColor.set()
roundedRect.fill()
}
}
|
mit
|
b4144e5fa284d871884488345d7614bd
| 28.382813 | 116 | 0.688913 | 4.3758 | false | false | false | false |
mkrd/Swift-Big-Integer
|
Tools/MG Math.swift
|
1
|
8837
|
/*
* ————————————————————————————————————————————————————————————————————————————
* MG Basic Math.swift
* ————————————————————————————————————————————————————————————————————————————
* Created by Marcel Kröker on 03.04.2015.
* Copyright © 2015 Marcel Kröker. All rights reserved.
*/
#if os(Linux)
import Glibc
import CBSD
#endif
import Foundation
infix operator **
func **(lhs: Double, rhs: Double) -> Double { return pow(lhs, rhs) }
func **(lhs: Int, rhs: Double) -> Double { return pow(Double(lhs), rhs) }
func **(lhs: Double, rhs: Int) -> Double { return pow(lhs, Double(rhs)) }
func **(lhs: Int, rhs: Int) -> Int
{
var res = 1
for _ in 0..<rhs { res *= lhs }
return res
}
/* Automatic type inference for operators that operate on Int and Double,
* use Double as the resulting type.
*/
func +(lhs: Double, rhs: Int) -> Double { return lhs + Double(rhs) }
func +(lhs: Int, rhs: Double) -> Double { return Double(lhs) + rhs }
func -(lhs: Double, rhs: Int) -> Double { return lhs - Double(rhs) }
func -(lhs: Int, rhs: Double) -> Double { return Double(lhs) - rhs }
func *(lhs: Double, rhs: Int) -> Double { return lhs * Double(rhs) }
func *(lhs: Int, rhs: Double) -> Double { return Double(lhs) * rhs }
func /(lhs: Double, rhs: Int) -> Double { return lhs / Double(rhs) }
func /(lhs: Int, rhs: Double) -> Double { return Double(lhs) / rhs }
public class math
{
init()
{
fatalError("math is purely static, you can't make an instance of it.")
}
/// Returns the logarithm of n to the base of b.
public static func lg(base b: Double, _ n: Double) -> Double
{
return log2(Double(n)) / log2(Double(b))
}
/// Returns the logarithm of n to the base of b.
public static func lg(base b: Int, _ n: Double) -> Double
{
return math.lg(base: Double(b), n)
}
/// Returns the logarithm of n to the base of b.
public static func lg(base b: Double, _ n: Int) -> Double
{
return math.lg(base: b, Double(n))
}
/// Returns the logarithm of n to the base of b.
public static func lg(base b: Int, _ n: Int) -> Double
{
return math.lg(base: Double(b), Double(n))
}
/// Returns the binomial coefficient of n and k.
public static func binomial(_ n: Int, _ k: Int) -> Int
{
if k == 0 { return 1 }
if n == 0 { return 0 }
return math.binomial(n - 1, k) + math.binomial(n - 1, k - 1)
}
/// Returns the greatest common divisor of a and b.
public static func gcd(_ a: Int, _ b: Int) -> Int
{
if b == 0 { return a }
return math.gcd(b, a % b)
}
/// Returns the lest common multiple of a and b.
public static func lcm(_ a: Int, _ b: Int) -> Int
{
return (a / math.gcd(a, b)) * b
}
/**
* Returns the number of digits of the input in the specified base.
* Positive and negative numbers are treated equally.
*/
public static func digitsCount(base b: Int, _ n: Int) -> Int
{
var n = abs(n)
var count = 0
while n != 0
{
n /= b
count += 1
}
return count
}
// Returns true iff n is a prime number.
public static func isPrime(_ n: Int) -> Bool
{
if n <= 3 { return n > 1 }
if n % 2 == 0 || n % 3 == 0 { return false }
var i = 5
while i * i <= n
{
if n % i == 0 || n % (i + 2) == 0
{
return false
}
i += 6
}
return true
}
/// Returns the n-th prime number. The first one is 2, etc.
public static func getPrime(_ n: Int) -> Int
{
precondition(n > 0, "There is no \(n)-th prime number")
var (prime, primeCount) = (2, 1)
while primeCount != n
{
prime += 1
if math.isPrime(prime) { primeCount += 1 }
}
return prime
}
/// Returns all primes that are smaller or equal to n. Works with the Sieve of Eratosthenes.
public static func primesThrough(_ n: Int) -> [Int]
{
if n < 2 { return [] }
// represent numbers 3,5,... that are <= n
var A = [Bool](repeating: true, count: n >> 1)
var (i, j, c) = (3, 0, 0)
while i * i <= n
{
if A[(i >> 1) - 1]
{
(c, j) = (1, i * i)
while j <= n
{
if j % 2 != 0 { A[(j >> 1) - 1] = false }
j = i * (i + c)
c += 1
}
}
i += 2
}
var res = [2]
i = 3
while i <= n
{
if A[(i >> 1) - 1] { res.append(i) }
i += 2
}
return res
}
/// Increments the input parameter until it is the next bigger prime.
public static func nextPrime( _ n: inout Int)
{
repeat { n += 1 } while !math.isPrime(n)
}
/// Returns a random integer within the specified range. The maximum range size is 2**32 - 1
public static func random(_ range: Range<Int>) -> Int
{
let offset = Int(range.lowerBound)
let delta = UInt32(range.upperBound - range.lowerBound)
return offset + Int(arc4random_uniform(delta))
}
/// Returns a random integer within the specified closed range.
public static func random(_ range: ClosedRange<Int>) -> Int
{
return math.random(Range(range))
}
/// Returns an array filled with n random integers within the specified range.
public static func random(_ range: Range<Int>, count: Int) -> [Int]
{
return [Int](repeating: 0, count: count).map{ _ in math.random(range) }
}
/// Returns an array filled with n random integers within the specified closed range.
public static func random(_ range: ClosedRange<Int>, count: Int) -> [Int]
{
return math.random(Range(range), count: count)
}
/// Returns a random Double within the specified closed range.
public static func random(_ range: ClosedRange<Double>) -> Double
{
let offset = range.lowerBound
let delta = range.upperBound - range.lowerBound
return offset + ((delta * Double(arc4random())) / Double(UInt32.max))
}
/// Returns an array filled with n random Doubles within the specified closed range.
public static func random(_ range: ClosedRange<Double>, count: Int) -> [Double]
{
return [Double](repeating: 0, count: count).map{ _ in math.random(range) }
}
/// Calculate a random value from a standard normal distribution with mean 0 and variance 1.
public static func randomStandardNormalDistributed() -> Double
{
var (x, y, l) = (0.0, 0.0, 0.0)
while l >= 1.0 || l == 0.0
{
x = math.random(-1.0...1.0)
y = math.random(-1.0...1.0)
l = pow(x, 2.0) + pow(y, 2.0)
}
return y * sqrt((-2.0 * log(l)) / l)
}
/// Generate count many random values from a normal distribution with the given mean and variance.
public static func randomFromNormalDist(_ mean: Double, _ variance: Double, _ count: Int) -> [Double]
{
let res = [Double](repeating: mean, count: count)
return res.map{ $0 + (variance * math.randomStandardNormalDistributed())
}
}
/// Multiple cases to select the instance space of a random string.
public enum LetterSet
{
case lowerCase
case upperCase
case numbers
case specialSymbols
case all
}
/**
Creates a random String from one or multiple sets of
letters.
- Parameter length: Number of characters in random string.
- Parameter letterSet: Specify desired letters as variadic
parameters:
- .All
- .Numbers
- .LowerCase
- .UpperCase
- .SpecialSymbols
*/
public static func randomString(_ length: Int, letterSet: LetterSet...) -> String
{
var letters = [String]()
var ranges = [CountableClosedRange<Int>]()
for ele in letterSet
{
switch ele
{
case .all:
ranges.append(33...126)
case .numbers:
ranges.append(48...57)
case .lowerCase:
ranges.append(97...122)
case .upperCase:
ranges.append(65...90)
case .specialSymbols:
ranges += [33...47, 58...64, 91...96, 123...126]
}
}
for range in ranges
{
for symbol in range
{
letters.append(String(describing: UnicodeScalar(symbol)!))
}
}
var res = ""
for _ in 0..<length
{
res.append(letters[math.random(0..<letters.count)])
}
return res
}
/// Factorize a number n into its prime factors.
public static func factorize(_ n: Int) -> [(factor: Int, count: Int)]
{
if math.isPrime(n) || n == 1 { return [(n, 1)] }
var n = n
var res = [(factor: Int, count: Int)]()
var nthPrime = 1
while true
{
math.nextPrime(&nthPrime)
if n % nthPrime == 0
{
var times = 1
n /= nthPrime
while n % nthPrime == 0
{
times += 1
n /= nthPrime
}
res.append((nthPrime, times))
if n == 1 { return res }
if math.isPrime(n)
{
res.append((n, 1))
return res
}
}
}
}
}
|
mit
|
3a26d4b5f0004fdbee9bbcea25597d8b
| 22.179348 | 102 | 0.585346 | 3.15342 | false | false | false | false |
ByteriX/BxInputController
|
BxInputController/Example/Controllers/ReviewController.swift
|
1
|
1642
|
//
// ReviewController.swift
// BxInputController
//
// Created by Sergey Balalaev on 02/02/17.
// Copyright © 2017 Byterix. All rights reserved.
//
import UIKit
class ReviewController: BxInputController
{
private var rateValue = BxInputRateRow(title: "Rate", value: 3.5)
private var disabledRateValue = BxInputRateRow(title: "Disabled rate", value: 2.5)
private var customRateValue = BxInputRateRow(title: "Custom rate", maxValue: 7, activeColor: UIColor.blue)
private var bigRateValue = BxInputRateRow(title: "Big rate", maxValue: 3, activeColor: UIColor.yellow)
private var textValue = BxInputSelectorTextRow(title: "Comments", placeholder: "This is your comments")
private var selectedTextValue = BxInputSelectorTextRow(title: "Selected Text", value: "Put your comments Please")
private var photosValue = BxInputSelectorPicturesRow(title: "Selected Photos")
override func viewDidLoad() {
super.viewDidLoad()
disabledRateValue.isEnabled = false
customRateValue.passiveColor = UIColor(white: 0.9, alpha: 1)
customRateValue.width = 100
bigRateValue.passiveColor = bigRateValue.activeColor.withAlphaComponent(0.2)
bigRateValue.width = 200
photosValue.maxSelectedCount = 8
self.sections = [
BxInputSection(headerText: "Rate", rows: [rateValue, disabledRateValue, customRateValue, bigRateValue]),
BxInputSection(headerText: "Text", rows: [textValue, selectedTextValue]),
BxInputSection(headerText: "Photos", rows: [photosValue]),
]
}
}
|
mit
|
4f05e3c723baf97425dc80bb940c1ac6
| 37.162791 | 117 | 0.689214 | 4.34127 | false | false | false | false |
Jackysonglanlan/Scripts
|
swift/xunyou_accelerator/Sources/src/constants/VpnConst.swift
|
1
|
1372
|
//
// VpnConst.swift
// xunyou-accelerator
//
// Created by jackysong on 2018/12/11.
// Copyright © 2018 xunyou.com. All rights reserved.
//
import Foundation
extension K {
public struct VPN {
/// 不要改动下面这个值! 必须是这个,否则 `NETunnelProviderManager` 的 `startVPNTunnel:options` 方法无法启动 Extension 进程
// public static let providerBundleIdentifier = "\(K.App.bundleID).PacketTunnel"
public static let tunnelingServerAddr = "127.0.0.1"
private static func getValueAsNSObject(for key: String, from data: [String: Any]) -> NSObject {
// data 里的值全部强制获取,否则报错,这是编程错误
return data[key] as! NSObject
}
/// PacketTunnel 配置项
public static let DefaultPacketTunnelConfig: [String: NSObject] = [
"MTU": 1400 as NSObject,
"tunnelRemoteAddress": "127.0.0.1" as NSObject,
"NEIPv4Settings": [["127.0.0.1"], ["255.255.255.255"]] as NSObject, // [0] = addr, [1] = subnetMasks
"NEDNSSettings": ["8.8.8.8"] as NSObject,
"NEProxyHTTP_Server": ["127.0.0.1", 9999] as NSObject,
"NEProxyHTTPS_Server": ["127.0.0.1", 9999] as NSObject,
"SOCKS5Adapter": ["127.0.0.1", 7777] as NSObject,
"TCPStack_HTTPProxyServer": ["127.0.0.1", UInt16(9999)] as NSObject, // 可以访问外网的 http 服务器
]
}
}
|
unlicense
|
71bb9df85d52ca5337bdc4f23512e4c9
| 31.076923 | 106 | 0.651479 | 3.104218 | false | false | false | false |
BGDigital/mckuai2.0
|
mckuai/mckuai/login/Nickname.swift
|
1
|
4168
|
//
// Nickname.swift
// mckuai
//
// Created by 夕阳 on 15/2/2.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
import Foundation
import UIKit
class Nickname:UIViewController,UIGestureRecognizerDelegate {
var manager = AFHTTPRequestOperationManager()
@IBOutlet weak var nick_editor: UITextField!
var username:String?
override func viewDidLoad() {
initNavigation()
self.navigationController?.navigationBar.tintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 1)
var barSize = self.navigationController?.navigationBar.frame
nick_editor.layer.borderColor = UIColor.whiteColor().CGColor
if(username != nil){
nick_editor.text = username
}
}
func initNavigation() {
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
let navigationTitleAttribute : NSDictionary = NSDictionary(objectsAndKeys: UIColor.whiteColor(),NSForegroundColorAttributeName)
self.navigationController?.navigationBar.titleTextAttributes = navigationTitleAttribute as [NSObject : AnyObject]
self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor(red: 0.247, green: 0.812, blue: 0.333, alpha: 1.00))
var back = UIBarButtonItem(image: UIImage(named: "nav_back"), style: UIBarButtonItemStyle.Bordered, target: self, action: "backToPage")
back.tintColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = back
self.navigationController?.interactivePopGestureRecognizer.delegate = self // 启用 swipe back
var sendButton = UIBarButtonItem()
sendButton.title = "保存"
sendButton.target = self
sendButton.action = Selector("save")
self.navigationItem.rightBarButtonItem = sendButton
}
func backToPage() {
self.navigationController?.popViewControllerAnimated(true)
}
class func changeNickname(ctl:UINavigationController,uname:String!){
var edit_nick = UIStoryboard(name: "profile_layout", bundle: nil).instantiateViewControllerWithIdentifier("edit_nick") as! Nickname
ctl.pushViewController(edit_nick, animated: true)
edit_nick.username = uname
}
func save(){
if let uname = nick_editor.text {
if uname != ""{
let dic = [
"flag" : NSString(string: "name"),
"userId": appUserIdSave,
"nickName" : uname
]
var hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
hud.labelText = "保存中"
manager.POST(saveUser_url,
parameters: dic,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
hud.hide(true)
MCUtils.showCustomHUD("保存信息成功", aType: .Success)
isLoginout = true
self.navigationController?.popViewControllerAnimated(true)
}else{
hud.hide(true)
MCUtils.showCustomHUD("保存信息失败", aType: .Error)
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
hud.hide(true)
MCUtils.showCustomHUD("保存信息失败", aType: .Error)
})
}
}
}
override func viewWillAppear(animated: Bool) {
MobClick.beginLogPageView("userInfoSetNickName")
self.tabBarController?.tabBar.hidden = true
}
override func viewWillDisappear(animated: Bool) {
self.tabBarController?.tabBar.hidden = false
MobClick.endLogPageView("userInfoSetNickName")
}
}
|
mit
|
cda2377a65965bb4ff734858db5f427e
| 35.39823 | 143 | 0.589008 | 5.258312 | false | false | false | false |
yusayusa/HighlightTextView
|
HighlightTextView/HighlightTextView.swift
|
1
|
3222
|
//
// HighlightTextView.swift
// HighlightTextView
//
// Created by KazukiYusa on 2016/10/10.
// Copyright © 2016年 KazukiYusa. All rights reserved.
//
import UIKit
extension UITextView {
private struct Condition {
let range: Range<Int>
let minHighlightColor: UIColor?
let maxHighlightColor: UIColor?
public init(range: Range<Int>, minHighlightColor: UIColor? = nil, maxHighlightColor: UIColor? = nil) {
self.range = range
self.minHighlightColor = minHighlightColor
self.maxHighlightColor = maxHighlightColor
}
}
private enum StoredProperties {
static var condition: Void?
static var subscription: Void?
}
private var condition: Condition? {
get {
return objc_getAssociatedObject(self, &StoredProperties.condition) as? Condition
}
set {
objc_setAssociatedObject(
self,
&StoredProperties.condition,
newValue,
.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
private var subscription: NSObjectProtocol? {
get {
return objc_getAssociatedObject(self, &StoredProperties.subscription) as? NSObjectProtocol
}
set {
objc_setAssociatedObject(
self,
&StoredProperties.subscription,
newValue,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
}
}
public func setHighlight(range: Range<Int>, minHighlightColor: UIColor? = nil, maxHighlightColor: UIColor? = nil) {
let condition = Condition(range: range, minHighlightColor: minHighlightColor, maxHighlightColor: maxHighlightColor)
self.condition = condition
highlight(condition: condition)
if let subscription = self.subscription {
NotificationCenter.default.removeObserver(subscription)
}
subscription = NotificationCenter.default.addObserver(
forName: NSTextStorage.didProcessEditingNotification,
object: textStorage,
queue: nil) { [weak self] _ in
self?.refreshHighlight()
}
}
private func highlight(condition: Condition) {
if markedTextRange != nil {
return
}
textStorage.beginEditing()
defer {
textStorage.endEditing()
}
let min = Swift.max(condition.range.lowerBound, 0)
let max = Swift.min(condition.range.upperBound, textStorage.length)
textStorage.addAttributes([.backgroundColor: UIColor.clear],
range: NSRange(location: 0,
length: textStorage.length))
if let color = condition.minHighlightColor, textStorage.length < min {
textStorage.addAttributes([.backgroundColor: color],
range: NSRange(location: 0,
length: textStorage.length))
}
else if let color = condition.maxHighlightColor, textStorage.length > max {
textStorage.addAttributes([.backgroundColor: color],
range: NSRange(location: max,
length: textStorage.length - max))
}
}
private func refreshHighlight() {
if let condition = condition {
highlight(condition: condition)
}
}
}
|
mit
|
14261fefa78903a8061fa3a8c5b95e6a
| 26.991304 | 119 | 0.630009 | 5.101426 | false | false | false | false |
taku33/FolioReaderPlus
|
Vendor/SMSegmentView/SMSegmentView.swift
|
2
|
10413
|
//
// SMSegmentView.swift
//
// Created by Si MA on 03/01/2015.
// Copyright (c) 2015 Si Ma. All rights reserved.
//
import UIKit
/*
Keys for segment properties
*/
// This is mainly for the top/bottom margin of the imageView
let keyContentVerticalMargin = "VerticalMargin"
// The colour when the segment is under selected/unselected
let keySegmentOnSelectionColour = "OnSelectionBackgroundColour"
let keySegmentOffSelectionColour = "OffSelectionBackgroundColour"
// The colour of the text in the segment for the segment is under selected/unselected
let keySegmentOnSelectionTextColour = "OnSelectionTextColour"
let keySegmentOffSelectionTextColour = "OffSelectionTextColour"
// The font of the text in the segment
let keySegmentTitleFont = "TitleFont"
enum SegmentOrganiseMode: Int {
case SegmentOrganiseHorizontal = 0
case SegmentOrganiseVertical
}
protocol SMSegmentViewDelegate: class {
func segmentView(segmentView: SMSegmentView, didSelectSegmentAtIndex index: Int)
}
class SMSegmentView: UIView, SMSegmentDelegate {
weak var delegate: SMSegmentViewDelegate?
var indexOfSelectedSegment = NSNotFound
var numberOfSegments = 0
var organiseMode: SegmentOrganiseMode = SegmentOrganiseMode.SegmentOrganiseHorizontal {
didSet {
self.setNeedsDisplay()
}
}
var segmentVerticalMargin: CGFloat = 5.0 {
didSet {
for segment in self.segments {
segment.verticalMargin = self.segmentVerticalMargin
}
}
}
// Segment Separator
var separatorColour: UIColor = UIColor.lightGrayColor() {
didSet {
self.setNeedsDisplay()
}
}
var separatorWidth: CGFloat = 1.0 {
didSet {
for segment in self.segments {
segment.separatorWidth = self.separatorWidth
}
self.updateFrameForSegments()
}
}
// Segment Colour
var segmentOnSelectionColour: UIColor = UIColor.darkGrayColor() {
didSet {
for segment in self.segments {
segment.onSelectionColour = self.segmentOnSelectionColour
}
}
}
var segmentOffSelectionColour: UIColor = UIColor.whiteColor() {
didSet {
for segment in self.segments {
segment.offSelectionColour = self.segmentOffSelectionColour
}
}
}
// Segment Title Text Colour & Font
var segmentOnSelectionTextColour: UIColor = UIColor.whiteColor() {
didSet {
for segment in self.segments {
segment.onSelectionTextColour = self.segmentOnSelectionTextColour
}
}
}
var segmentOffSelectionTextColour: UIColor = UIColor.darkGrayColor() {
didSet {
for segment in self.segments {
segment.offSelectionTextColour = self.segmentOffSelectionTextColour
}
}
}
var segmentTitleFont: UIFont = UIFont.systemFontOfSize(17.0) {
didSet {
for segment in self.segments {
segment.titleFont = self.segmentTitleFont
}
}
}
override var frame: CGRect {
didSet {
self.updateFrameForSegments()
}
}
var segments: Array<SMSegment> = Array()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.layer.masksToBounds = true
}
init(frame: CGRect, separatorColour: UIColor, separatorWidth: CGFloat, segmentProperties: Dictionary<String, AnyObject>?) {
self.separatorColour = separatorColour
self.separatorWidth = separatorWidth
if let margin = segmentProperties?[keyContentVerticalMargin] as? Float {
self.segmentVerticalMargin = CGFloat(margin)
}
if let onSelectionColour = segmentProperties?[keySegmentOnSelectionColour] as? UIColor {
self.segmentOnSelectionColour = onSelectionColour
}
else {
self.segmentOnSelectionColour = UIColor.darkGrayColor()
}
if let offSelectionColour = segmentProperties?[keySegmentOffSelectionColour] as? UIColor {
self.segmentOffSelectionColour = offSelectionColour
}
else {
self.segmentOffSelectionColour = UIColor.whiteColor()
}
if let onSelectionTextColour = segmentProperties?[keySegmentOnSelectionTextColour] as? UIColor {
self.segmentOnSelectionTextColour = onSelectionTextColour
}
else {
self.segmentOnSelectionTextColour = UIColor.whiteColor()
}
if let offSelectionTextColour = segmentProperties?[keySegmentOffSelectionTextColour] as? UIColor {
self.segmentOffSelectionTextColour = offSelectionTextColour
}
else {
self.segmentOffSelectionTextColour = UIColor.darkGrayColor()
}
if let titleFont = segmentProperties?[keySegmentTitleFont] as? UIFont {
self.segmentTitleFont = titleFont
}
else {
self.segmentTitleFont = UIFont.systemFontOfSize(17.0)
}
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
self.layer.masksToBounds = true
}
func addSegmentWithTitle(title: String?, onSelectionImage: UIImage?, offSelectionImage: UIImage?) {
let segment = SMSegment(separatorWidth: self.separatorWidth, verticalMargin: self.segmentVerticalMargin, onSelectionColour: self.segmentOnSelectionColour, offSelectionColour: self.segmentOffSelectionColour, onSelectionTextColour: self.segmentOnSelectionTextColour, offSelectionTextColour: self.segmentOffSelectionTextColour, titleFont: self.segmentTitleFont)
segment.index = self.segments.count
self.segments.append(segment)
self.updateFrameForSegments()
segment.delegate = self
segment.title = title
segment.onSelectionImage = onSelectionImage
segment.offSelectionImage = offSelectionImage
self.addSubview(segment)
self.numberOfSegments = self.segments.count
}
func updateFrameForSegments() {
if self.segments.count == 0 {
return
}
let count = self.segments.count
if count > 1 {
if self.organiseMode == SegmentOrganiseMode.SegmentOrganiseHorizontal {
let segmentWidth = (self.frame.size.width - self.separatorWidth*CGFloat(count-1)) / CGFloat(count)
var originX: CGFloat = 0.0
for segment in self.segments {
segment.frame = CGRect(x: originX, y: 0.0, width: segmentWidth, height: self.frame.size.height)
originX += segmentWidth + self.separatorWidth
}
}
else {
let segmentHeight = (self.frame.size.height - self.separatorWidth*CGFloat(count-1)) / CGFloat(count)
var originY: CGFloat = 0.0
for segment in self.segments {
segment.frame = CGRect(x: 0.0, y: originY, width: self.frame.size.width, height: segmentHeight)
originY += segmentHeight + self.separatorWidth
}
}
}
else {
self.segments[0].frame = CGRect(x: 0.0, y: 0.0, width: self.frame.size.width, height: self.frame.size.height)
}
self.setNeedsDisplay()
}
// MARK: SMSegment Delegate
func selectSegment(segment: SMSegment) {
if self.indexOfSelectedSegment != NSNotFound {
let previousSelectedSegment = self.segments[self.indexOfSelectedSegment]
previousSelectedSegment.setSelected(false)
}
self.indexOfSelectedSegment = segment.index
segment.setSelected(true)
self.delegate?.segmentView(self, didSelectSegmentAtIndex: segment.index)
}
// MARK: Actions
func selectSegmentAtIndex(index: Int) {
assert(index >= 0 && index < self.segments.count, "Index at \(index) is out of bounds")
self.selectSegment(self.segments[index])
}
func deselectSegment() {
if self.indexOfSelectedSegment != NSNotFound {
let segment = self.segments[self.indexOfSelectedSegment]
segment.setSelected(false)
self.indexOfSelectedSegment = NSNotFound
}
}
// MARK: Drawing Segment Separators
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
self.drawSeparatorWithContext(context!)
}
func drawSeparatorWithContext(context: CGContextRef) {
CGContextSaveGState(context)
if self.segments.count > 1 {
let path = CGPathCreateMutable()
if self.organiseMode == SegmentOrganiseMode.SegmentOrganiseHorizontal {
var originX: CGFloat = self.segments[0].frame.size.width + self.separatorWidth/2.0
for index in 1..<self.segments.count {
CGPathMoveToPoint(path, nil, originX, 0.0)
CGPathAddLineToPoint(path, nil, originX, self.frame.size.height)
originX += self.segments[index].frame.width + self.separatorWidth
}
}
else {
var originY: CGFloat = self.segments[0].frame.size.height + self.separatorWidth/2.0
for index in 1..<self.segments.count {
CGPathMoveToPoint(path, nil, 0.0, originY)
CGPathAddLineToPoint(path, nil, self.frame.size.width, originY)
originY += self.segments[index].frame.height + self.separatorWidth
}
}
CGContextAddPath(context, path)
CGContextSetStrokeColorWithColor(context, self.separatorColour.CGColor)
CGContextSetLineWidth(context, self.separatorWidth)
CGContextDrawPath(context, CGPathDrawingMode.Stroke)
}
CGContextRestoreGState(context)
}
}
|
bsd-3-clause
|
c2e6eafcaf8695a780fd596ed3926506
| 34.783505 | 366 | 0.624796 | 5.318182 | false | false | false | false |
tqtifnypmb/huntaway
|
Sources/Huntaway/Response.swift
|
1
|
9726
|
//
// Response.swift
// Huntaway
//
// The MIT License (MIT)
//
// Copyright (c) 2016 tqtifnypmb
//
// 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 class Response {
typealias onCompleteHandler = (resp : Response, error: NSError?) -> Void
typealias onBeginHandler = () -> Void
typealias onProcessHandler = (progress: Progress) -> Void
typealias onDownloadCompleteHandler = (url: NSURL) -> Void
typealias onDataReceivedHandler = () -> Void
private let session: Session
private var resumeData: NSData? = nil
private var completed: Int32 = 0
private let condition: NSCondition
//FIXME: thread-safe issue ??
private var ticked = false
let task: NSURLSessionTask
let request: Request
var HTTPHeaders: [String: String]? = nil
var HTTPCookies: [String: String]? = nil
var HTTPStatusCode: Int = 0
var errorDescription: NSError? = nil
var receivedData: [UInt8]? = nil
var HTTPRedirectHistory: [NSURL]? = nil
var authTriedUsername: [String]? = nil
var completeHandler: onCompleteHandler? = nil
var beginHandler: onBeginHandler? = nil
var processHandler: onProcessHandler? = nil
var downloadHandler: onDownloadCompleteHandler? = nil
var dataReceivedHandler: onDataReceivedHandler? = nil
var waked_up_by_system_completion_handler: (() -> Void)? = nil
init(task: NSURLSessionTask, request: Request, session: Session) {
self.task = task
self.request = request
self.condition = NSCondition()
self.session = session
}
/// Status code
/// Block if response is not ready
public var statusCode: Int {
guard self.ticked else { return 0 }
waitForComplete()
return self.HTTPStatusCode
}
/// string description of statusCode
/// Block if response is not ready
public var reason: String {
guard self.ticked else { return "" }
return NSHTTPURLResponse.localizedStringForStatusCode(self.statusCode)
}
/// HTTP request's URL
public var requestURL: NSURL {
return self.request.URL
}
/// HTTP response's URL
/// Block if response is not ready
public var URL: NSURL? {
guard self.ticked else { return nil }
waitForComplete()
return self.task.response!.URL
}
/// Network error
/// Block if response is not ready
public var error: NSError? {
guard self.ticked else { return nil }
waitForComplete()
return self.errorDescription
}
/// HTTP cookies
/// Block if response is not ready
public var cookies: [String: String]? {
guard self.ticked else { return nil }
waitForComplete()
return self.HTTPCookies
}
/// HTTP response's headers
/// Block if response is not ready
public var headers: [String: String]? {
guard self.ticked else { return nil }
waitForComplete()
return self.HTTPHeaders
}
/// Raw data of HTTP response's body.
/// Block if response is not ready
public var body: [UInt8]? {
guard self.ticked else { return nil }
waitForComplete()
return self.receivedData
}
public var bodyJson: AnyObject? {
guard self.ticked else { return nil }
guard var body = self.body else { return nil }
let data = NSData(bytes: &body, length: body.count)
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments)
} catch {
return nil
}
}
/// String representatino of HTTP response's body
public var text: String? {
guard self.ticked else { return nil }
waitForComplete()
guard let data = self.receivedData else { return nil }
return String(bytes: data, encoding: NSUTF8StringEncoding)
}
public var redirectHistory: [NSURL]? {
if !self.request.rememberRedirectHistory && self.ticked { return nil }
waitForComplete()
return self.HTTPRedirectHistory
}
/// Close this response.
/// After called, this response is no
/// longer valid. You should always
/// call this method when you're done with
/// response
public func close() {
self.session.removeResponse(self)
self.removeHooks()
}
/// Set onComplete callback.
/// This hook will be called as soon as response get ready
///
/// **Note** This hook should be set before response get ticked.
/// Hooks set after response tick might not be called
public func onComplete(completeHandler: (resp : Response, error: NSError?) -> Void) {
if !self.ticked {
self.completeHandler = completeHandler
} else {
self.condition.lock()
self.completeHandler = completeHandler
self.condition.unlock()
}
}
/// Set onBegin callback.
/// This hook will be called as soon as request get sent
///
/// **Note** This hook should be set before response get ticked.
/// Hooks set after response tick might not be called
public func onBegin(beginHandler: () -> Void) {
guard !self.ticked else { return }
self.beginHandler = beginHandler
}
/// Set onProcess callback.
/// This hook will be called everytime when data sent or data received
///
/// **Note** This hook should be set before response get ticked.
/// Hooks set after response tick might not be called
public func onProcess(processHandler: (progress: Progress) -> Void) {
guard !self.ticked else { return }
self.processHandler = processHandler
}
/// This hook will be called when download is completed.
public func onDownloadComplete(downloadHandler: ((url: NSURL) -> Void)) {
guard !self.ticked else { return }
self.downloadHandler = downloadHandler
}
/// This hook will be called everytime data received.
public func onDataReceived(dataReceivedHandler: (() -> Void)) {
guard !self.ticked else { return }
self.dataReceivedHandler = dataReceivedHandler
}
/// Tick to let things happen
public func tick(completeHandler: ((resp : Response, error: NSError?) -> Void)? = nil) -> Response {
guard !self.ticked else { return self }
if let completeHandler = completeHandler {
self.onComplete(completeHandler)
}
return self.do_tick()
}
/// Tick to start download
public func tick(downloadCompleteHandler: ((url: NSURL) -> Void)) -> Response {
guard !self.ticked else { return self }
self.onDownloadComplete(downloadCompleteHandler)
return self.do_tick()
}
private func do_tick() -> Response {
self.ticked = true
self.task.resume()
if let handler = self.beginHandler {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) { handler() }
}
return self
}
/// Test whether response is ready to use.
/// This function *Never* block
public func isReady() -> Bool {
return OSAtomicCompareAndSwap32(1, 1, &self.completed)
}
/// Suspend the ongoing task.
/// A task, while suspended, produces no network traffic and is not subject to timeouts.
/// A download task can continue transferring data at a later time.
///All other tasks must start over when resumed.
public func suspend() {
self.task.suspend()
}
/// Cancels the task.
public func cancel() {
self.task.cancel()
self.removeHooks()
}
/// Resumes the task, if it is suspended.
public func resume() {
self.task.resume()
}
func markCompleted() {
OSAtomicCompareAndSwap32(0, 1, &self.completed)
self.condition.broadcast()
}
private func waitForComplete() {
if OSAtomicCompareAndSwap32(1, 1, &self.completed) {
return
}
self.condition.lock()
while !OSAtomicCompareAndSwap32(1, 1, &self.completed) {
self.condition.wait()
}
self.condition.unlock()
}
private func removeHooks() {
self.completeHandler = nil
self.processHandler = nil
self.dataReceivedHandler = nil
self.downloadHandler = nil
self.beginHandler = nil
}
}
|
mit
|
55c77580ffef7e410a255eb61b8d1577
| 30.996711 | 106 | 0.624614 | 4.732847 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.