repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
benlangmuir/swift | test/Interop/SwiftToCxx/methods/mutating-method-in-cxx.swift | 2 | 4131 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Methods -clang-header-expose-public-decls -emit-clang-header-path %t/methods.h
// RUN: %FileCheck %s < %t/methods.h
// RUN: %check-interop-cxx-header-in-clang(%t/methods.h)
public struct LargeStruct {
var x1, x2, x3, x4, x5, x6: Int
public func dump() {
print("\(x1), \(x2), \(x3), \(x4), \(x5), \(x6)")
}
public mutating func double() {
x1 *= 2
x2 *= 2
x3 *= 2
x4 *= 2
x5 *= 2
x6 *= 2
}
public mutating func scale(_ x: Int, _ y: Int) -> LargeStruct {
x1 *= x
x2 *= y
x3 *= x
x4 *= y
x5 *= x
x6 *= y
return self
}
}
public struct SmallStruct {
var x: Float
public func dump() {
print("small x = \(x);")
}
public mutating func scale(_ y: Float) -> SmallStruct {
x *= y
return SmallStruct(x: x / y)
}
public mutating func invert() {
x = -x
}
}
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV4dumpyyF(SWIFT_CONTEXT const void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // dump()
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV6doubleyyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // double()
// CHECK: SWIFT_EXTERN void $s7Methods11LargeStructV5scaleyACSi_SitF(SWIFT_INDIRECT_RESULT void * _Nonnull, ptrdiff_t x, ptrdiff_t y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // scale(_:_:)
// CHECK: SWIFT_EXTERN void $s7Methods11SmallStructV4dumpyyF(struct swift_interop_passStub_Methods_float_0_4 _self) SWIFT_NOEXCEPT SWIFT_CALL; // dump()
// CHECK: SWIFT_EXTERN struct swift_interop_returnStub_Methods_float_0_4 $s7Methods11SmallStructV5scaleyACSfF(float y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // scale(_:)
// CHECK: SWIFT_EXTERN void $s7Methods11SmallStructV6invertyyF(SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // invert()
// CHECK: class LargeStruct final {
// CHECK: inline LargeStruct(LargeStruct &&) = default;
// CHECK-NEXT: inline void dump() const;
// CHECK-NEXT: inline void double_();
// CHECK-NEXT: inline LargeStruct scale(swift::Int x, swift::Int y);
// CHECK-NEXT: private
// CHECK: class SmallStruct final {
// CHECK: inline SmallStruct(SmallStruct &&) = default;
// CHECK-NEXT: inline void dump() const;
// CHECK-NEXT: inline SmallStruct scale(float y);
// CHECK-NEXT: inline void invert();
// CHECK-NEXT: private:
public func createLargeStruct() -> LargeStruct {
return LargeStruct(x1: 1, x2: -5, x3: 9, x4: 11, x5: 0xbeef, x6: -77)
}
public func createSmallStruct(x: Float) -> SmallStruct {
return SmallStruct(x: x)
}
// CHECK: inline void LargeStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Methods11LargeStructV4dumpyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline void LargeStruct::double_() {
// CHECK-NEXT: return _impl::$s7Methods11LargeStructV6doubleyyF(_getOpaquePointer());
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct LargeStruct::scale(swift::Int x, swift::Int y) {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s7Methods11LargeStructV5scaleyACSi_SitF(result, x, y, _getOpaquePointer());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline void SmallStruct::dump() const {
// CHECK-NEXT: return _impl::$s7Methods11SmallStructV4dumpyyF(_impl::swift_interop_passDirect_Methods_float_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline SmallStruct SmallStruct::scale(float y) {
// CHECK-NEXT: return _impl::_impl_SmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Methods_float_0_4(result, _impl::$s7Methods11SmallStructV5scaleyACSfF(y, _getOpaquePointer()));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline void SmallStruct::invert() {
// CHECK-NEXT: return _impl::$s7Methods11SmallStructV6invertyyF(_getOpaquePointer());
// CHECK-NEXT: }
| apache-2.0 | 06449f37b50cb28d771e563d6d1f3254 | 38.721154 | 212 | 0.658678 | 3.394412 | false | false | false | false |
bitjammer/swift | test/SILGen/local_recursion.swift | 1 | 5349 | // RUN: %target-swift-frontend -parse-as-library -emit-silgen %s | %FileCheck %s
// RUN: %target-swift-frontend -enable-astscope-lookup -parse-as-library -emit-silgen %s | %FileCheck %s
// CHECK-LABEL: sil hidden @_T015local_recursionAAySi_Si1ytF : $@convention(thin) (Int, Int) -> () {
// CHECK: bb0([[X:%0]] : $Int, [[Y:%1]] : $Int):
func local_recursion(_ x: Int, y: Int) {
func self_recursive(_ a: Int) {
self_recursive(x + a)
}
// Invoke local functions by passing all their captures.
// CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE:@_T015local_recursionAAySi_Si1ytF14self_recursiveL_ySiF]]
// CHECK: apply [[SELF_RECURSIVE_REF]]([[X]], [[X]])
self_recursive(x)
// CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE]]
// CHECK: [[CLOSURE:%.*]] = partial_apply [[SELF_RECURSIVE_REF]]([[X]])
// CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]]
// CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]]
let sr = self_recursive
// CHECK: apply [[CLOSURE_COPY]]([[Y]])
// CHECK: end_borrow [[BORROWED_CLOSURE]] from [[CLOSURE]]
sr(y)
func mutually_recursive_1(_ a: Int) {
mutually_recursive_2(x + a)
}
func mutually_recursive_2(_ b: Int) {
mutually_recursive_1(y + b)
}
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1:@_T015local_recursionAAySi_Si1ytF20mutually_recursive_1L_ySiF]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]([[X]], [[Y]], [[X]])
mutually_recursive_1(x)
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]]
_ = mutually_recursive_1
func transitive_capture_1(_ a: Int) -> Int {
return x + a
}
func transitive_capture_2(_ b: Int) -> Int {
return transitive_capture_1(y + b)
}
// CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE:@_T015local_recursionAAySi_Si1ytF20transitive_capture_2L_S2iF]]
// CHECK: apply [[TRANS_CAPTURE_REF]]([[X]], [[X]], [[Y]])
transitive_capture_2(x)
// CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE]]
// CHECK: [[CLOSURE:%.*]] = partial_apply [[TRANS_CAPTURE_REF]]([[X]], [[Y]])
// CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]]
// CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]]
let tc = transitive_capture_2
// CHECK: apply [[CLOSURE_COPY]]([[X]])
// CHECK: end_borrow [[BORROWED_CLOSURE]] from [[CLOSURE]]
tc(x)
// CHECK: [[CLOSURE_REF:%.*]] = function_ref @_T015local_recursionAAySi_Si1ytFySicfU_
// CHECK: apply [[CLOSURE_REF]]([[X]], [[X]], [[Y]])
let _: Void = {
self_recursive($0)
transitive_capture_2($0)
}(x)
// CHECK: [[CLOSURE_REF:%.*]] = function_ref @_T015local_recursionAAySi_Si1ytFySicfU0_
// CHECK: [[CLOSURE:%.*]] = partial_apply [[CLOSURE_REF]]([[X]], [[Y]])
// CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [[CLOSURE]]
// CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]]
// CHECK: apply [[CLOSURE_COPY]]([[X]])
// CHECK: end_borrow [[BORROWED_CLOSURE]] from [[CLOSURE]]
let f: (Int) -> () = {
self_recursive($0)
transitive_capture_2($0)
}
f(x)
}
// CHECK: sil shared [[SELF_RECURSIVE]]
// CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int):
// CHECK: [[SELF_REF:%.*]] = function_ref [[SELF_RECURSIVE]]
// CHECK: apply [[SELF_REF]]({{.*}}, [[X]])
// CHECK: sil shared [[MUTUALLY_RECURSIVE_1]]
// CHECK: bb0([[A:%0]] : $Int, [[Y:%1]] : $Int, [[X:%2]] : $Int):
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_2:@_T015local_recursionAAySi_Si1ytF20mutually_recursive_2L_ySiF]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[X]], [[Y]])
// CHECK: sil shared [[MUTUALLY_RECURSIVE_2]]
// CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int):
// CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]]
// CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[Y]], [[X]])
// CHECK: sil shared [[TRANS_CAPTURE_1:@_T015local_recursionAAySi_Si1ytF20transitive_capture_1L_S2iF]]
// CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int):
// CHECK: sil shared [[TRANS_CAPTURE]]
// CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int):
// CHECK: [[TRANS_CAPTURE_1_REF:%.*]] = function_ref [[TRANS_CAPTURE_1]]
// CHECK: apply [[TRANS_CAPTURE_1_REF]]({{.*}}, [[X]])
func plus<T>(_ x: T, _ y: T) -> T { return x }
func toggle<T, U>(_ x: T, _ y: U) -> U { return y }
func generic_local_recursion<T, U>(_ x: T, y: U) {
func self_recursive(_ a: T) {
self_recursive(plus(x, a))
}
self_recursive(x)
_ = self_recursive
func transitive_capture_1(_ a: T) -> U {
return toggle(a, y)
}
func transitive_capture_2(_ b: U) -> U {
return transitive_capture_1(toggle(b, x))
}
transitive_capture_2(y)
_ = transitive_capture_2
func no_captures() {}
no_captures()
_ = no_captures
func transitive_no_captures() {
no_captures()
}
transitive_no_captures()
_ = transitive_no_captures
}
func local_properties(_ x: Int, y: Int) -> Int {
var self_recursive: Int {
return x + self_recursive
}
var transitive_capture_1: Int {
return x
}
var transitive_capture_2: Int {
return transitive_capture_1 + y
}
func transitive_capture_fn() -> Int {
return transitive_capture_2
}
return self_recursive + transitive_capture_fn()
}
| apache-2.0 | dab0983c3720487b0a236744f69b1b47 | 33.960784 | 144 | 0.598056 | 3.023742 | false | false | false | false |
gregomni/swift | test/Distributed/distributed_actor_isolation_and_tasks.swift | 9 | 2421 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend-emit-module -emit-module-path %t/FakeDistributedActorSystems.swiftmodule -module-name FakeDistributedActorSystems -disable-availability-checking %S/Inputs/FakeDistributedActorSystems.swift
// RUN: %target-swift-frontend -typecheck -verify -disable-availability-checking -I %t 2>&1 %s
// REQUIRES: concurrency
// REQUIRES: distributed
import Distributed
import FakeDistributedActorSystems
@available(SwiftStdlib 5.5, *)
typealias DefaultDistributedActorSystem = FakeActorSystem
struct SomeLogger {}
struct Logger {
let label: String
func info(_: String) {}
}
distributed actor Philosopher {
let log: Logger
// expected-note@-1{{access to property 'log' is only permitted within distributed actor 'Philosopher'}}
var variable = 12
var variable_fromDetach = 12
let INITIALIZED: Int
let outside: Int = 1
init(system: FakeActorSystem) {
self.log = Logger(label: "name")
self.INITIALIZED = 1
}
distributed func dist() -> Int {}
func test() {
_ = self.id
_ = self.actorSystem
Task {
_ = self.id
_ = self.actorSystem
self.log.info("READY!")
_ = self.variable
_ = self.dist()
}
Task.detached {
_ = self.id
_ = self.actorSystem
// This is an interesting case, since we have a real local `self` and
// yet are not isolated to the same actor in this detached task...
// the call to it is implicitly async, however it is NOT implicitly throwing
// because we KNOW this is a local call -- and there is no system in
// between that will throw.
_ = await self.dist() // notice lack of 'try' even though 'distributed func'
_ = self.variable_fromDetach // expected-error{{expression is 'async' but is not marked with 'await'}}
// expected-note@-1{{property access is 'async'}}
_ = await self.variable_fromDetach // okay, we know we're on the local node
}
}
}
func test_outside(system: FakeActorSystem) async throws {
_ = try await Philosopher(system: system).dist()
_ = Philosopher(system: system).log // expected-error{{distributed actor-isolated property 'log' can not be accessed from a non-isolated context}}
_ = Philosopher(system: system).id
_ = Philosopher(system: system).actorSystem
}
func test_outside_isolated(phil: isolated Philosopher) async throws {
phil.log.info("works on isolated")
}
| apache-2.0 | 560611ebd13c9ade4b2ddbe2773e9ff9 | 31.716216 | 219 | 0.690211 | 3.99505 | false | false | false | false |
exponent/exponent | packages/expo-dev-launcher/ios/Manifest/EXDevLauncherManifestHelper.swift | 2 | 2039 | // Copyright 2015-present 650 Industries. All rights reserved.
import UIKit
@objc
public class EXDevLauncherManifestHelper: NSObject {
private static func defaultOrientationForOrientationMask(_ orientationMask: UIInterfaceOrientationMask) -> UIInterfaceOrientation {
if orientationMask.contains(.portrait) {
return UIInterfaceOrientation.portrait
} else if orientationMask.contains(.landscapeLeft) {
return UIInterfaceOrientation.landscapeLeft
} else if orientationMask.contains(.landscapeRight) {
return UIInterfaceOrientation.landscapeRight
} else if orientationMask.contains(.portraitUpsideDown) {
return UIInterfaceOrientation.portraitUpsideDown
}
return UIInterfaceOrientation.unknown
}
@objc
public static func exportManifestOrientation(_ orientation: String?) -> UIInterfaceOrientation {
var orientationMask = UIInterfaceOrientationMask.all
if orientation == "portrait" {
orientationMask = .portrait
} else if orientation == "landscape" {
orientationMask = .landscape
}
return defaultOrientationForOrientationMask(orientationMask)
}
@objc
public static func hexStringToColor(_ hexString: String?) -> UIColor? {
guard var hexString = hexString else {
return nil
}
if hexString.count != 7 || !hexString.starts(with: "#") {
return nil
}
hexString.removeFirst()
var rgbValue: UInt64 = 0
Scanner(string: hexString).scanHexInt64(&rgbValue)
return UIColor(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: 1.0)
}
@objc
@available(iOS 12.0, *)
public static func exportManifestUserInterfaceStyle(_ userInterfaceStyle: String?) -> UIUserInterfaceStyle {
switch userInterfaceStyle {
case "light":
return .light
case "dark":
return .dark
default:
return .unspecified
}
}
}
| bsd-3-clause | 746c3e17dba3a597acf4851eda862120 | 29.893939 | 133 | 0.691025 | 5.009828 | false | false | false | false |
kevin0571/Ditto | Sources/Serializer.swift | 1 | 3508 | //
// Serializer.swift
// Ditto
//
// Created by Kevin Lin on 23/10/16.
// Copyright © 2016 Kevin. All rights reserved.
//
import Foundation
extension Serializable {
/**
Serialize the current object to a JSON object.
Non-convertible field of the current object will be ignored.
- returns: `JSONObject`
*/
public func serialize() -> JSONObject {
let mapping = self.serializableMapping()
let mirror = Mirror(reflecting: self)
var jsonObject = JSONObject()
for child in mirror.children {
guard let label = child.label else {
continue
}
guard let jsonField = mapping[label] else {
continue
}
let value = child.value
if let serializable = value as? Serializable {
jsonObject[jsonField] = serializable.serialize() as JSONObject
} else if let convertible = value as? Convertible {
jsonObject[jsonField] = convertible.convert()
}
}
return jsonObject
}
public func serialize() -> String {
return stringify(jsonValue: serialize() as JSONObject)
}
public func serialize() -> Data? {
return serialize().data(using: .utf8)
}
}
extension Array where Element: Serializable {
public func serialize() -> JSONArray {
var jsonArray = JSONArray()
for serializable in self {
jsonArray.append(serializable.serialize() as JSONObject)
}
return jsonArray
}
public func serialize() -> String {
return stringify(jsonValue: serialize() as JSONArray)
}
public func serialize() -> Data? {
return serialize().data(using: .utf8)
}
}
extension Array where Element: Convertible {
public func serialize() -> JSONArray {
var jsonArray = JSONArray()
for convertible in self {
jsonArray.append(convertible.convert())
}
return jsonArray
}
public func serialize() -> String {
return stringify(jsonValue: serialize() as JSONArray)
}
public func serialize() -> Data? {
return serialize().data(using: .utf8)
}
}
// MARK: Helpers
private func stringify(jsonValue: JSONValue?) -> String {
guard let jsonValue = jsonValue else {
return "null"
}
let string: String
switch jsonValue {
case is Integer: fallthrough
case is Float: fallthrough
case is Double: fallthrough
case is Bool: fallthrough
case is NSNumber:
string = "\(jsonValue)"
case is JSONObject:
let jsonObject = jsonValue as! JSONObject
var objectString = "{"
var count = 0
let totalCount = jsonObject.count
for (key, value) in jsonObject {
count += 1
objectString += "\"\(key)\":\(stringify(jsonValue: value))\(count == totalCount ? "" : ",")"
}
objectString += "}"
string = objectString
case is JSONArray:
let jsonArray = jsonValue as! JSONArray
var arrayString = "["
var count = 0
let totalCount = jsonArray.count
for object in jsonArray {
count += 1
arrayString += "\(stringify(jsonValue: object))\(count == totalCount ? "" : ",")"
}
arrayString += "]"
string = arrayString
default:
string = "\"\(jsonValue)\""
}
return string
}
| mit | e6731c8a4565f55475f42d98176d8e04 | 26.833333 | 104 | 0.57371 | 5.075253 | false | false | false | false |
mamouneyya/TheSkillsProof | Pods/p2.OAuth2/Sources/Base/OAuth2.swift | 2 | 25220 | //
// OAuth2.swift
// OAuth2
//
// Created by Pascal Pfiffner on 6/4/14.
// Copyright 2014 Pascal Pfiffner
//
// 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
/**
Base class for specific OAuth2 authentication flow implementations.
*/
public class OAuth2: OAuth2Base {
/// The grant type represented by the class, e.g. "authorization_code" for code grants.
public class var grantType: String {
return "__undefined"
}
/// The response type expected from an authorize call, e.g. "code" for code grants.
public class var responseType: String? {
return nil
}
/// Settings related to the client-server relationship.
public let clientConfig: OAuth2ClientConfig
/// Client-side authorization options.
public var authConfig = OAuth2AuthConfig()
/// The client id.
public final var clientId: String? {
get { return clientConfig.clientId }
set { clientConfig.clientId = newValue }
}
/// The client secret, usually only needed for code grant.
public final var clientSecret: String? {
get { return clientConfig.clientSecret }
set { clientConfig.clientSecret = newValue }
}
/// The name of the client, as used during dynamic client registration. Use "client_name" during initalization to set.
public var clientName: String? {
get { return clientConfig.clientName }
}
/// The URL to authorize against.
public final var authURL: NSURL {
get { return clientConfig.authorizeURL }
}
/// The URL string where we can exchange a code for a token; if nil `authURL` will be used.
public final var tokenURL: NSURL? {
get { return clientConfig.tokenURL }
}
/// The scope currently in use.
public var scope: String? {
get { return clientConfig.scope }
set { clientConfig.scope = newValue }
}
/// The redirect URL string to use.
public var redirect: String? {
get { return clientConfig.redirect }
set { clientConfig.redirect = newValue }
}
/// Context for the current auth dance.
var context = OAuth2ContextStore()
/// The receiver's access token.
public var accessToken: String? {
get { return clientConfig.accessToken }
set { clientConfig.accessToken = newValue }
}
/// The access token's expiry date.
public var accessTokenExpiry: NSDate? {
get { return clientConfig.accessTokenExpiry }
set { clientConfig.accessTokenExpiry = newValue }
}
/// The receiver's long-time refresh token.
public var refreshToken: String? {
get { return clientConfig.refreshToken }
set { clientConfig.refreshToken = newValue }
}
/// Closure called on successful authentication on the main thread.
public final var onAuthorize: ((parameters: OAuth2JSON) -> Void)?
/// When authorization fails (if error is not nil) or is cancelled, this block is executed on the main thread.
public final var onFailure: ((error: ErrorType?) -> Void)?
/**
Closure called after onAuthorize OR onFailure, on the main thread; useful for cleanup operations.
- parameter wasFailure: Bool indicating success or failure
- parameter error: ErrorType describing the reason for failure, as supplied to the `onFailure` callback. If it is nil and `wasFailure`
is true, the process was aborted.
*/
public final var afterAuthorizeOrFailure: ((wasFailure: Bool, error: ErrorType?) -> Void)?
/// Same as `afterAuthorizeOrFailure`, but only for internal use and called right BEFORE the public variant.
final var internalAfterAuthorizeOrFailure: ((wasFailure: Bool, error: ErrorType?) -> Void)?
/// If non-nil, will be called before performing dynamic client registration, giving you a chance to instantiate your own registrar.
public final var onBeforeDynamicClientRegistration: (NSURL -> OAuth2DynReg?)?
/**
Designated initializer.
The following settings keys are currently supported:
- client_id (string)
- client_secret (string), usually only needed for code grant
- authorize_uri (URL-string)
- token_uri (URL-string), if omitted the authorize_uri will be used to obtain tokens
- redirect_uris (list of URL-strings)
- scope (string)
- client_name (string)
- registration_uri (URL-string)
- logo_uri (URL-string)
- keychain (bool, true by default, applies to using the system keychain)
- verbose (bool, false by default, applies to client logging)
- secret_in_body (bool, false by default, forces the flow to use the request body for the client secret)
- token_assume_unexpired (bool, true by default, whether to use access tokens that do not come with an "expires_in" parameter)
- title (string, to be shown in views shown by the framework)
*/
public override init(settings: OAuth2JSON) {
clientConfig = OAuth2ClientConfig(settings: settings)
// auth configuration options
if let inBody = settings["secret_in_body"] as? Bool {
authConfig.secretInBody = inBody
}
if let ttl = settings["title"] as? String {
authConfig.ui.title = ttl
}
super.init(settings: settings)
}
// MARK: - Keychain Integration
/** Overrides base implementation to return the authorize URL. */
public override func keychainServiceName() -> String {
return authURL.description
}
override func updateFromKeychainItems(items: [String : NSCoding]) {
for message in clientConfig.updateFromStorableItems(items) {
logIfVerbose(message)
}
authConfig.secretInBody = (clientConfig.endpointAuthMethod == OAuth2EndpointAuthMethod.ClientSecretPost)
}
override func storableCredentialItems() -> [String : NSCoding]? {
return clientConfig.storableCredentialItems()
}
override func storableTokenItems() -> [String : NSCoding]? {
return clientConfig.storableTokenItems()
}
public override func forgetClient() {
super.forgetClient()
clientConfig.forgetCredentials()
}
public override func forgetTokens() {
super.forgetTokens()
clientConfig.forgetTokens()
}
// MARK: - Authorization
/**
Use this method, together with `authConfig`, to obtain an access token.
This method will first check if the client already has an unexpired access token (possibly from the keychain), if not and it's able to
use a refresh token it will try to use the refresh token. If this fails it will check whether the client has a client_id and show the
authorize screen if you have `authConfig` set up sufficiently. If `authConfig` is not set up sufficiently this method will end up
calling the `onFailure` callback. If client_id is not set but a "registration_uri" has been provided, a dynamic client registration will
be attempted and if it succees, an access token will be requested.
- parameter params: Optional key/value pairs to pass during authorization
*/
public final func authorize(params params: OAuth2StringDict? = nil) {
isAuthorizing = true
tryToObtainAccessTokenIfNeeded() { success in
if success {
self.didAuthorize(OAuth2JSON())
}
else {
self.registerClientIfNeeded() { json, error in
if let error = error {
self.didFail(error)
}
else {
do {
assert(NSThread.isMainThread())
try self.doAuthorize(params: params)
}
catch let error {
self.didFail(error)
}
}
}
}
}
}
/**
Shortcut function to start embedded authorization from the given context (a UIViewController on iOS, an NSWindow on OS X).
This method sets `authConfig.authorizeEmbedded = true` and `authConfig.authorizeContext = <# context #>`, then calls `authorize()`
*/
public func authorizeEmbeddedFrom(context: AnyObject, params: OAuth2StringDict? = nil) {
authConfig.authorizeEmbedded = true
authConfig.authorizeContext = context
authorize(params: params)
}
/**
If the instance has an accessToken, checks if its expiry time has not yet passed. If we don't have an expiry date we assume the token
is still valid.
*/
public func hasUnexpiredAccessToken() -> Bool {
if let access = accessToken where !access.isEmpty {
if let expiry = accessTokenExpiry {
return expiry == expiry.laterDate(NSDate())
}
return clientConfig.accessTokenAssumeUnexpired
}
return false
}
/**
Indicates, in the callback, whether the client has been able to obtain an access token that is likely to still
work (but there is no guarantee).
- parameter callback: The callback to call once the client knows whether it has an access token or not
*/
func tryToObtainAccessTokenIfNeeded(callback: ((success: Bool) -> Void)) {
if hasUnexpiredAccessToken() {
callback(success: true)
}
else {
logIfVerbose("No access token, maybe I can refresh")
doRefreshToken({ successParams, error in
if nil != successParams {
callback(success: true)
}
else {
if let err = error {
self.logIfVerbose("\(err)")
}
callback(success: false)
}
})
}
}
/**
Method to actually start authorization. The public `authorize()` method only proceeds to this method if there is no valid access token
and if optional client registration succeeds.
Can be overridden in subclasses to perform an authorization dance different from directing the user to a website.
- parameter params: Optional key/value pairs to pass during authorization
*/
func doAuthorize(params params: OAuth2StringDict? = nil) throws {
if self.authConfig.authorizeEmbedded {
try self.authorizeEmbeddedWith(self.authConfig, params: params)
}
else {
try self.openAuthorizeURLInBrowser(params)
}
}
/**
Constructs an authorize URL with the given parameters.
It is possible to use the `params` dictionary to override internally generated URL parameters, use it wisely.
Subclasses generally provide shortcut methods to receive an appropriate authorize (or token) URL.
- parameter redirect: The redirect URI string to supply. If it is nil, the first value of the settings' `redirect_uris` entries is
used. Must be present in the end!
- parameter params: Any additional parameters as dictionary with string keys and values that will be added to the query part
- parameter asTokenURL: Whether this will go to the token_uri endpoint, not the authorize_uri
- returns: NSURL to be used to start or continue the OAuth dance
*/
func authorizeURLWithParams(params: OAuth2StringDict, asTokenURL: Bool = false) throws -> NSURL {
// compose URL base
let base = asTokenURL ? (clientConfig.tokenURL ?? clientConfig.authorizeURL) : clientConfig.authorizeURL
let comp = NSURLComponents(URL: base, resolvingAgainstBaseURL: true)
if nil == comp || "https" != comp!.scheme {
throw OAuth2Error.NotUsingTLS
}
// compose the URL query component
comp!.percentEncodedQuery = OAuth2.queryStringFor(params)
if let final = comp!.URL {
logIfVerbose("Authorizing against \(final.description)")
return final
}
throw OAuth2Error.Generic("Failed to create authorize URL from components: \(comp)")
}
/**
Most convenient method if you want the authorize URL to be created as defined in your settings dictionary.
- parameter params: Optional, additional URL params to supply to the request
- returns: NSURL to be used to start the OAuth dance
*/
public func authorizeURL(params: OAuth2StringDict? = nil) throws -> NSURL {
return try authorizeURLWithRedirect(nil, scope: nil, params: params)
}
/**
Convenience method to be overridden by and used from subclasses.
- parameter redirect: The redirect URI string to supply. If it is nil, the first value of the settings' `redirect_uris` entries is
used. Must be present in the end!
- parameter scope: The scope to request
- parameter params: Any additional parameters as dictionary with string keys and values that will be added to the
query part
- returns: NSURL to be used to start the OAuth dance
*/
public func authorizeURLWithRedirect(redirect: String?, scope: String?, params: OAuth2StringDict?) throws -> NSURL {
guard let redirect = (redirect ?? clientConfig.redirect) else {
throw OAuth2Error.NoRedirectURL
}
guard let clientId = clientId where !clientId.isEmpty else {
throw OAuth2Error.NoClientId
}
var prms = params ?? OAuth2StringDict()
prms["redirect_uri"] = redirect
prms["client_id"] = clientId
prms["state"] = context.state
if let scope = scope ?? clientConfig.scope {
prms["scope"] = scope
}
if let responseType = self.dynamicType.responseType {
prms["response_type"] = responseType
}
context.redirectURL = redirect
return try authorizeURLWithParams(prms, asTokenURL: false)
}
/**
Subclasses override this method to extract information from the supplied redirect URL.
*/
public func handleRedirectURL(redirect: NSURL) throws {
throw OAuth2Error.Generic("Abstract class use")
}
// MARK: - Refresh Token
/**
Generate the URL to be used for the token request when we have a refresh token.
This will set "grant_type" to "refresh_token", add the refresh token, then forward to `authorizeURLWithParams()` to fill the remaining
parameters.
- parameter params: Additional parameters to pass during token refresh
*/
func tokenURLForTokenRefresh(params: OAuth2StringDict? = nil) throws -> NSURL {
guard let clientId = clientId where !clientId.isEmpty else {
throw OAuth2Error.NoClientId
}
guard let refreshToken = clientConfig.refreshToken where !refreshToken.isEmpty else {
throw OAuth2Error.NoRefreshToken
}
var urlParams = params ?? OAuth2StringDict()
urlParams["grant_type"] = "refresh_token"
urlParams["refresh_token"] = refreshToken
urlParams["client_id"] = clientId
if let secret = clientConfig.clientSecret {
if authConfig.secretInBody {
urlParams["client_secret"] = secret
}
else {
urlParams.removeValueForKey("client_id") // will be in the Authorization header
}
}
return try authorizeURLWithParams(urlParams, asTokenURL: true)
}
/**
Create a request for token refresh.
*/
func tokenRequestForTokenRefresh() throws -> NSMutableURLRequest {
let url = try tokenURLForTokenRefresh()
return try tokenRequestWithURL(url)
}
/**
If there is a refresh token, use it to receive a fresh access token.
- parameter callback: The callback to call after the refresh token exchange has finished
*/
public func doRefreshToken(callback: ((successParams: OAuth2JSON?, error: ErrorType?) -> Void)) {
do {
let post = try tokenRequestForTokenRefresh()
logIfVerbose("Using refresh token to receive access token from \(post.URL?.description ?? "nil")")
performRequest(post) { data, status, error in
do {
guard let data = data else {
throw error ?? OAuth2Error.NoDataInResponse
}
let json = try self.parseRefreshTokenResponse(data)
if status < 400 {
self.logIfVerbose("Did use refresh token for access token [\(nil != self.clientConfig.accessToken)]")
if self.useKeychain {
self.storeTokensToKeychain()
}
callback(successParams: json, error: nil)
}
else {
throw OAuth2Error.Generic("\(status)")
}
}
catch let error {
self.logIfVerbose("Error parsing refreshed access token: \(error)")
callback(successParams: nil, error: error)
}
}
}
catch let error {
callback(successParams: nil, error: error)
}
}
// MARK: - Registration
/**
Use OAuth2 dynamic client registration to register the client, if needed.
Returns immediately if the receiver's `clientId` is nil (with error = nil) or if there is no registration URL (with error). Otherwise
calls `onBeforeDynamicClientRegistration()` -- if it is non-nil -- and uses the returned `OAuth2DynReg` instance -- if it is non-nil.
If both are nil, instantiates a blank `OAuth2DynReg` instead, then attempts client registration.
- parameter callback: The callback to call on the main thread; if both json and error is nil no registration was attempted; error is nil
on success
*/
func registerClientIfNeeded(callback: ((json: OAuth2JSON?, error: ErrorType?) -> Void)) {
if nil != clientId {
callOnMainThread() {
callback(json: nil, error: nil)
}
}
else if let url = clientConfig.registrationURL {
let dynreg = onBeforeDynamicClientRegistration?(url) ?? OAuth2DynReg()
dynreg.registerClient(self) { json, error in
callOnMainThread() {
callback(json: json, error: error)
}
}
}
else {
callOnMainThread() {
callback(json: nil, error: OAuth2Error.NoRegistrationURL)
}
}
}
// MARK: - Callbacks
/// Flag used internally to determine whether authorization is going on at all and can be aborted.
private var isAuthorizing = false
/**
Internally used on success. Calls the `onAuthorize` and `afterAuthorizeOrFailure` callbacks on the main thread.
*/
func didAuthorize(parameters: OAuth2JSON) {
isAuthorizing = false
if useKeychain {
storeTokensToKeychain()
}
callOnMainThread() {
self.onAuthorize?(parameters: parameters)
self.internalAfterAuthorizeOrFailure?(wasFailure: false, error: nil)
self.afterAuthorizeOrFailure?(wasFailure: false, error: nil)
}
}
/**
Internally used on error. Calls the `onFailure` and `afterAuthorizeOrFailure` callbacks on the main thread.
*/
func didFail(error: ErrorType?) {
isAuthorizing = false
var finalError = error
if let error = error {
logIfVerbose("\(error)")
if let oae = error as? OAuth2Error where .RequestCancelled == oae {
finalError = nil
}
}
callOnMainThread() {
self.onFailure?(error: finalError)
self.internalAfterAuthorizeOrFailure?(wasFailure: true, error: error)
self.afterAuthorizeOrFailure?(wasFailure: true, error: error)
}
}
// MARK: - Requests
/**
Return an OAuth2Request, a NSMutableURLRequest subclass, that has already been signed and can be used against
your OAuth2 endpoint.
This method prefers cached data and specifies a timeout interval of 20 seconds.
- parameter forURL: The URL to create a request for
- returns: OAuth2Request for the given URL
*/
public func request(forURL url: NSURL) -> OAuth2Request {
return OAuth2Request(URL: url, oauth: self, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 20)
}
/**
Allows to abort authorization currently in progress.
*/
public func abortAuthorization() {
if !abortTask() && isAuthorizing {
logIfVerbose("Aborting authorization")
didFail(nil)
}
}
// MARK: - Utilities
/**
Creates a POST request with x-www-form-urlencoded body created from the supplied URL's query part.
*/
func tokenRequestWithURL(url: NSURL) throws -> NSMutableURLRequest {
guard let clientId = clientId where !clientId.isEmpty else {
throw OAuth2Error.NoClientId
}
let comp = NSURLComponents(URL: url, resolvingAgainstBaseURL: true)
assert(comp != nil, "It seems NSURLComponents cannot parse \(url)");
let body = comp!.percentEncodedQuery
comp!.query = nil
let req = NSMutableURLRequest(URL: comp!.URL!)
req.HTTPMethod = "POST"
req.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
req.setValue("application/json", forHTTPHeaderField: "Accept")
req.HTTPBody = body?.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// add Authorization header if we have a client secret (even if it's empty)
if let secret = clientSecret where !authConfig.secretInBody {
logIfVerbose("Adding “Authorization” header as “Basic client-key:client-secret”")
let pw = "\(clientId.wwwFormURLEncodedString):\(secret.wwwFormURLEncodedString)"
if let utf8 = pw.dataUsingEncoding(NSUTF8StringEncoding) {
req.setValue("Basic \(utf8.base64EncodedStringWithOptions([]))", forHTTPHeaderField: "Authorization")
}
else {
throw OAuth2Error.UTF8EncodeError
}
}
return req
}
// MARK: - Response Parsing
/**
Parse response data returned while exchanging the code for a token.
This method extracts token data and fills the receiver's properties accordingly. If the response contains an "error" key, will parse the
error and throw it.
- parameter data: NSData returned from the call
- returns: An OAuth2JSON instance with token data; may contain additional information
*/
func parseAccessTokenResponse(data: NSData) throws -> OAuth2JSON {
let dict = try parseJSON(data)
return try parseAccessTokenResponse(dict)
}
/**
Parse response data returned while exchanging the code for a token.
This method extracts token data and fills the receiver's properties accordingly. If the response contains an "error" key, will parse the
error and throw it. The method is final to ensure correct order of error parsing and not parsing the response if an error happens. This
is not possible in overrides. Instead, override the various `assureXy(dict:)` methods, especially `assureAccessTokenParamsAreValid()`.
- parameter params: Dictionary data parsed from the response
- returns: An OAuth2JSON instance with token data; may contain additional information
*/
final func parseAccessTokenResponse(params: OAuth2JSON) throws -> OAuth2JSON {
try assureNoErrorInResponse(params)
try assureCorrectBearerType(params)
try assureAccessTokenParamsAreValid(params)
clientConfig.updateFromResponse(params)
return params
}
/**
Parse response data returned while using a refresh token.
This method extracts token data and fills the receiver's properties accordingly. If the response contains an "error" key, will parse the
error and throw it.
- parameter data: NSData returned from the call
- returns: An OAuth2JSON instance with token data; may contain additional information
*/
func parseRefreshTokenResponse(data: NSData) throws -> OAuth2JSON {
let dict = try parseJSON(data)
return try parseRefreshTokenResponse(dict)
}
/**
Parse response data returned while using a refresh token.
This method extracts token data and fills the receiver's properties accordingly. If the response contains an "error" key, will parse the
error and throw it. The method is final to ensure correct order of error parsing and not parsing the response if an error happens. This
is not possible in overrides. Instead, override the various `assureXy(dict:)` methods, especially `assureRefreshTokenParamsAreValid()`.
- parameter json: Dictionary data parsed from the response
- returns: An OAuth2JSON instance with token data; may contain additional information
*/
final func parseRefreshTokenResponse(dict: OAuth2JSON) throws -> OAuth2JSON {
try assureNoErrorInResponse(dict)
try assureCorrectBearerType(dict)
try assureRefreshTokenParamsAreValid(dict)
clientConfig.updateFromResponse(dict)
return dict
}
/**
This method checks `state`, throws `OAuth2Error.InvalidState` if it doesn't match. Resets state if it matches.
*/
func assureMatchesState(params: OAuth2JSON) throws {
if !context.matchesState(params["state"] as? String) {
throw OAuth2Error.InvalidState
}
context.resetState()
}
/**
Throws unless "token_type" is "bearer" (case-insensitive).
*/
func assureCorrectBearerType(params: OAuth2JSON) throws {
if let tokType = params["token_type"] as? String {
if "bearer" == tokType.lowercaseString {
return
}
throw OAuth2Error.UnsupportedTokenType("Only “bearer” token is supported, but received “\(tokType)”")
}
throw OAuth2Error.NoTokenType
}
/**
Called when parsing the access token response. Does nothing by default, implicit grant flows check state.
*/
public func assureAccessTokenParamsAreValid(params: OAuth2JSON) throws {
}
/**
Called when parsing the refresh token response. Does nothing by default.
*/
public func assureRefreshTokenParamsAreValid(params: OAuth2JSON) throws {
}
}
/**
Class, internally used, to store current authorization context, such as state and redirect-url.
*/
class OAuth2ContextStore {
/// Currently used redirect_url.
var redirectURL: String?
/// The current state.
internal(set) var _state = ""
/**
The state sent to the server when requesting a token.
We internally generate a UUID and use the first 8 chars if `_state` is empty.
*/
var state: String {
if _state.isEmpty {
_state = NSUUID().UUIDString
_state = _state[_state.startIndex..<_state.startIndex.advancedBy(8)] // only use the first 8 chars, should be enough
}
return _state
}
/**
Checks that given state matches the internal state.
- parameter state: The state to check (may be nil)
- returns: true if state matches, false otherwise or if given state is nil.
*/
func matchesState(state: String?) -> Bool {
if let st = state {
return st == _state
}
return false
}
/**
Resets current state so it gets regenerated next time it's needed.
*/
func resetState() {
_state = ""
}
}
| mit | ed85b2c6344aebc199aa5834f296868c | 32.6502 | 137 | 0.726869 | 3.978532 | false | true | false | false |
tatsuyamoriguchi/PoliPoli | View Controller/PlayAudio.swift | 1 | 1384 | //
// PlayAudio.swift
// Poli
//
// Created by Tatsuya Moriguchi on 8/6/18.
// Copyright © 2018 Becko's Inc. All rights reserved.
//
import Foundation
import AVFoundation
import UIKit
class PlayAudio {
static let sharedInstance = PlayAudio()
private var player: AVAudioPlayer!
func playClick(fileName: String, fileExt: String) {
//guard let url = Bundle.main.url(forResource: fileName, withExtension: fileExt) else {return}
if let asset = NSDataAsset(name: fileName) {
do {
/*
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)), mode: <#AVAudioSession.Mode#>)
*/
try AVAudioSession.sharedInstance().setActive(true)
//player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)
player = try AVAudioPlayer(data:asset.data, fileTypeHint: "caf")
guard let player = player else { return }
player.play()
} catch {
print(error)
}
}
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
return input.rawValue
}
| gpl-3.0 | 2e7da0fdc348a225783a2e9f71d1cd2c | 31.162791 | 198 | 0.628344 | 4.904255 | false | false | false | false |
pradeepb28/iOS-LabelAnimationOnTextField | LabelAnimationOnTextField/LabelAnimationOnTextField/UITextField+PBLabelTF.swift | 1 | 2541 | //
// UITextField+PBLabelTF.swift
// LabelAnimationOnTextField
//
// Created by Pradeep Burugu on 1/13/16.
// Copyright © 2016 Pradeep Burugu. All rights reserved.
//
import UIKit
extension UITextField {
static func animatePBLabelTF(textField:UITextField, align:String, position:String, fontName:String, fontSize:CGFloat, red:CGFloat, green:CGFloat, blue:CGFloat)->UILabel?{
var labelPosition:CGRect?
var labelAnimatePosition:CGRect?
var label:UILabel?
if textField.tag != 100 {
// Label Position - top
if position == "top" || position == "TOP" || position == "Top" {
labelPosition = CGRectMake(textField.frame.origin.x, textField.frame.origin.y, textField.frame.size.width, 10)
labelAnimatePosition = CGRectMake(textField.frame.origin.x, textField.frame.origin.y-11, textField.frame.size.width, 10)
// Label Position = bottom
} else if position == "bottom" || position == "BOTTOM" || position == "Bottom" {
labelPosition = CGRectMake(textField.frame.origin.x, textField.frame.origin.y+textField.frame.size.height, textField.frame.size.width, 10);
labelAnimatePosition = CGRectMake(textField.frame.origin.x, textField.frame.origin.y+textField.frame.size.height+1, textField.frame.size.width, 10);
}
label = UILabel(frame: labelPosition!)
//Label Alignment - left
if align == "left" || align == "LEFT" || align == "Left" {
label!.textAlignment = NSTextAlignment.Left
} // Label Alignment - right
else if align == "right" || align == "RIGHT" || align == "Right" {
label!.textAlignment = NSTextAlignment.Right
}
label!.userInteractionEnabled = false
textField.tag = 100
label!.font = UIFont(name: fontName, size: fontSize)
label!.font = label!.font.fontWithSize(fontSize)
label!.numberOfLines = 1
label!.baselineAdjustment = UIBaselineAdjustment.AlignBaselines
label!.textColor = UIColor(red: red, green: green, blue: blue, alpha: 0.75)
label!.text = textField.placeholder
UIView.animateWithDuration(0.10, animations: { () -> Void in
label!.frame = labelAnimatePosition!
}, completion: { (Bool) -> Void in
label!.frame = labelAnimatePosition!
})
}
return label
}
} | mit | 774b5f5a163e8cc147e3411ca80649a1 | 48.823529 | 174 | 0.60748 | 4.503546 | false | false | false | false |
Ro6Fish/BDChannelPack | baiduchannelpack/AppDelegate.swift | 1 | 2399 | //
// AppDelegate.swift
// baiduchannelpack
//
// Created by luokaiwen on 16/8/17.
// Copyright © 2016年 luokaiwen. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
// Insert code here to initialize your application
// let apkHandlePath = NSBundle.mainBundle().pathForResource("ApkHandle", ofType: "jar")
//
// let task = NSTask()
// task.launchPath = "/usr/bin/java"
// task.arguments = ["-jar", "/Users/luokaiwen/Desktop/ApkHandle.jar", "unzip", "/Users/luokaiwen/Desktop/test/ddd_driver.apk"];
// let pipe = NSPipe()
// task.standardOutput = pipe
// task.standardError = pipe
// task.launch()
// let data = pipe.fileHandleForReading.readDataToEndOfFile()
// let output = NSString(data: data, encoding: NSUTF8StringEncoding)
//
// print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:")
// print(output)
// print("task.launchPath" + task.launchPath!)
// print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx:")
//
// // 存入选择的目录
// NSUserDefaults.standardUserDefaults().setObject("hahaasdasda1212", forKey: "abc")
// NSUserDefaults.standardUserDefaults().synchronize()
//
// // 获取以前选过的目录
// if let text = NSUserDefaults.standardUserDefaults().objectForKey("abc") as? String {
// print(text)
// }
//
// print(NSBundle.mainBundle().resourcePath)
// print(NSBundle.mainBundle().pathForResource("ApkChannel", ofType: "jar"))
//
//
//
// let date = NSDate()
// let interval = date.timeIntervalSince1970
// let intervalStr = String(format: "%.f", interval);
// // var index = intervalStr.substringToIndex("7".endIndex)
//
// print(intervalStr.substringToIndex(intervalStr.startIndex.advancedBy(7)))
//
// let a = "/Users/luokaiwen/Desktop/test.apk".stringByReplacingOccurrencesOfString("test.apk", withString: "")
//
// print("我勒个去" + a)
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
}
| mit | 2659fa89e54fb6798f54db2461f94129 | 33.647059 | 135 | 0.620119 | 4.199643 | false | false | false | false |
therealbnut/swift | test/expr/cast/bridged.swift | 3 | 4002 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
// Test casting through a class type to a bridged value type.
// FIXME: Should go into the standard library.
public extension _ObjectiveCBridgeable {
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self {
var result: Self?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
class NSObject { }
class BridgedClass : NSObject {
}
class SubclassOfBridgedClass : BridgedClass { }
struct BridgedStruct : _ObjectiveCBridgeable {
func _bridgeToObjectiveC() -> BridgedClass {
return BridgedClass()
}
static func _forceBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?
) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?
) -> Bool {
return true
}
}
func testBridgeDowncast(_ obj: AnyObject, objOpt: AnyObject?,
objImplicitOpt: AnyObject!) -> BridgedStruct? {
let s1Opt = obj as? BridgedStruct
var s2Opt = objOpt as? BridgedStruct
var s3Opt = objImplicitOpt as? BridgedStruct
// Make sure we seem to have the right result type.
if s1Opt != nil { return s1Opt }
s2Opt = s1Opt
s2Opt = s3Opt
s3Opt = s1Opt
_ = s2Opt
return s1Opt
}
func testBridgeIsa(_ obj: AnyObject, objOpt: AnyObject?,
objImplicitOpt: AnyObject!) {
if obj is BridgedStruct { }
if objOpt is BridgedStruct { }
if objImplicitOpt is BridgedStruct { }
}
func testBridgeDowncastSuperclass(_ obj: NSObject, objOpt: NSObject?,
objImplicitOpt: NSObject!)
-> BridgedStruct? {
_ = obj as? BridgedStruct
_ = objOpt as? BridgedStruct
_ = objImplicitOpt as? BridgedStruct
}
func testBridgeDowncastExact(_ obj: BridgedClass, objOpt: BridgedClass?,
objImplicitOpt: BridgedClass!) -> BridgedStruct? {
_ = obj as? BridgedStruct // expected-warning{{conditional cast from 'BridgedClass' to 'BridgedStruct' always succeeds}}
_ = objOpt as? BridgedStruct // expected-warning{{conditional downcast from 'BridgedClass?' to 'BridgedStruct' is a bridging conversion; did you mean to use 'as'?}}{{14-17=as}}{{31-31=?}}
_ = objImplicitOpt as? BridgedStruct // expected-warning{{conditional downcast from 'BridgedClass!' to 'BridgedStruct' is a bridging conversion; did you mean to use 'as'?}}{{22-25=as}}{{39-39=?}}
_ = obj as! BridgedStruct // expected-warning{{forced cast from 'BridgedClass' to 'BridgedStruct' always succeeds; did you mean to use 'as'?}}{{11-14=as}}
_ = objOpt as! BridgedStruct // expected-warning{{forced cast from 'BridgedClass?' to 'BridgedStruct' only unwraps and bridges; did you mean to use '!' with 'as'?}}{{13-13=!}}{{14-17=as}}
_ = objImplicitOpt as! BridgedStruct // expected-warning{{forced cast from 'BridgedClass!' to 'BridgedStruct' only unwraps and bridges; did you mean to use '!' with 'as'?}}{{21-21=!}}{{22-25=as}}
_ = obj is BridgedStruct // expected-warning{{'is' test is always true}}
_ = objOpt is BridgedStruct // expected-warning{{checking a value with optional type 'BridgedClass?' against dynamic type 'BridgedStruct' succeeds whenever the value is non-'nil'; did you mean to use '!= nil'?}}{{14-30=!= nil}}
_ = objImplicitOpt is BridgedStruct // expected-warning{{checking a value with optional type 'BridgedClass!' against dynamic type 'BridgedStruct' succeeds whenever the value is non-'nil'; did you mean to use '!= nil'?}}{{22-38=!= nil}}
}
func testExplicitBridging(_ object: BridgedClass, value: BridgedStruct) {
var object = object
var value = value
object = value as BridgedClass
value = object as BridgedStruct
}
func testBridgingFromSubclass(_ obj: SubclassOfBridgedClass) {
_ = obj as! BridgedStruct // expected-warning{{forced cast from 'SubclassOfBridgedClass' to 'BridgedStruct' always succeeds; did you mean to use 'as'?}} {{11-14=as}}
_ = obj as BridgedStruct
}
| apache-2.0 | 403d92c52783b09a7b4209ce3dded1b1 | 39.836735 | 237 | 0.696152 | 4.3125 | false | true | false | false |
grandiere/box | box/View/Boards/VBoardsBarSelector.swift | 1 | 7109 | import UIKit
class VBoardsBarSelector:UIView
{
private weak var controller:CBoards!
private weak var itemScore:VBoardsBarSelectorItem!
private weak var itemKills:VBoardsBarSelectorItem!
private weak var viewIndicator:VBoardsBarSelectorIndicator!
private weak var layoutIndicatorLeft:NSLayoutConstraint!
private var gestureLastX:CGFloat?
private let kItemMultiplier:CGFloat = 0.5
private let kIndicatorMultiplier:CGFloat = 0.5
private let kBackgroundMargin:CGFloat = 1
private let kAnimationDuration:TimeInterval = 0.4
init(controller:CBoards)
{
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let viewBackground:VBoardsBarSelectorBackground = VBoardsBarSelectorBackground()
let itemScore:VBoardsBarSelectorItem = VBoardsBarSelectorItem(
title:NSLocalizedString("VBoardsBarSelector_itemScore", comment:""))
itemScore.addTarget(
self,
action:#selector(actionScore(sender:)),
for:UIControlEvents.touchUpInside)
self.itemScore = itemScore
let itemKills:VBoardsBarSelectorItem = VBoardsBarSelectorItem(
title:NSLocalizedString("VBoardsBarSelector_itemKills", comment:""))
itemKills.addTarget(
self,
action:#selector(actionKills(sender:)),
for:UIControlEvents.touchUpInside)
self.itemKills = itemKills
let viewIndicator:VBoardsBarSelectorIndicator = VBoardsBarSelectorIndicator()
self.viewIndicator = viewIndicator
let panGesture:UIPanGestureRecognizer = UIPanGestureRecognizer(
target:self,
action:#selector(actionPanning(sender:)))
addSubview(viewBackground)
addSubview(viewIndicator)
addSubview(itemScore)
addSubview(itemKills)
addGestureRecognizer(panGesture)
NSLayoutConstraint.equals(
view:viewBackground,
toView:self,
margin:kBackgroundMargin)
NSLayoutConstraint.equalsVertical(
view:viewIndicator,
toView:self)
layoutIndicatorLeft = NSLayoutConstraint.leftToLeft(
view:viewIndicator,
toView:self)
NSLayoutConstraint.width(
view:viewIndicator,
toView:self,
multiplier:kIndicatorMultiplier)
NSLayoutConstraint.equalsVertical(
view:itemScore,
toView:self)
NSLayoutConstraint.leftToLeft(
view:itemScore,
toView:self)
NSLayoutConstraint.width(
view:itemScore,
toView:self,
multiplier:kItemMultiplier)
NSLayoutConstraint.equalsVertical(
view:itemKills,
toView:self)
NSLayoutConstraint.rightToRight(
view:itemKills,
toView:self)
NSLayoutConstraint.width(
view:itemKills,
toView:self,
multiplier:kItemMultiplier)
buttonScore()
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: actions
func actionScore(sender button:UIButton)
{
indicatorScore(animated:true)
}
func actionKills(sender button:UIButton)
{
indicatorKills(animated:true)
}
func actionPanning(sender panGesture:UIPanGestureRecognizer)
{
switch panGesture.state
{
case UIGestureRecognizerState.began:
gestureBegan(gesture:panGesture)
break
case UIGestureRecognizerState.possible,
UIGestureRecognizerState.changed:
gestureMoving(gesture:panGesture)
break
case UIGestureRecognizerState.cancelled,
UIGestureRecognizerState.ended,
UIGestureRecognizerState.failed:
gestureEnded(gesture:panGesture)
break
}
}
//MARK: private
private func indicatorMaxX() -> CGFloat
{
return bounds.midX
}
private func gestureBegan(gesture:UIPanGestureRecognizer)
{
let location:CGPoint = gesture.location(in:self)
gestureLastX = location.x
}
private func gestureMoving(gesture:UIPanGestureRecognizer)
{
guard
let gestureLastX:CGFloat = self.gestureLastX
else
{
return
}
let location:CGPoint = gesture.location(in:self)
let newX:CGFloat = location.x
let deltaX:CGFloat = newX - gestureLastX
let maxX:CGFloat = indicatorMaxX()
let midX:CGFloat = maxX / 2.0
var indicatorNewX:CGFloat = layoutIndicatorLeft.constant + deltaX
if indicatorNewX < 0
{
indicatorNewX = 0
}
else if indicatorNewX > maxX
{
indicatorNewX = maxX
}
if indicatorNewX > midX
{
buttonKills()
}
else
{
buttonScore()
}
layoutIndicatorLeft.constant = indicatorNewX
self.gestureLastX = newX
}
private func gestureEnded(gesture:UIPanGestureRecognizer)
{
let maxX:CGFloat = indicatorMaxX()
let midX:CGFloat = maxX / 2.0
if layoutIndicatorLeft.constant > midX
{
indicatorKills(animated:true)
}
else
{
indicatorScore(animated:true)
}
}
private func buttonScore()
{
itemScore.isSelected = true
itemKills.isSelected = false
}
private func buttonKills()
{
itemScore.isSelected = false
itemKills.isSelected = true
}
private func indicatorScore(animated:Bool)
{
controller.model.sortScore()
buttonScore()
let duration:TimeInterval
if animated
{
duration = kAnimationDuration
}
else
{
duration = 0
}
layoutIndicatorLeft.constant = 0
UIView.animate(withDuration:duration)
{ [weak self] in
self?.layoutIfNeeded()
}
}
private func indicatorKills(animated:Bool)
{
controller.model.sortKills()
buttonKills()
let duration:TimeInterval
if animated
{
duration = kAnimationDuration
}
else
{
duration = 0
}
layoutIndicatorLeft.constant = indicatorMaxX()
UIView.animate(withDuration:duration)
{ [weak self] in
self?.layoutIfNeeded()
}
}
}
| mit | baaf42a8e53ea05c3752c69b94e3f88c | 25.427509 | 88 | 0.573358 | 5.562598 | false | false | false | false |
SwiftKit/Torch | Source/Utils/TorchMetadata.swift | 1 | 994 | //
// TorchMetadata.swift
// Torch
//
// Created by Filip Dolnik on 20.07.16.
// Copyright © 2016 Brightify. All rights reserved.
//
import CoreData
@objc(TorchMetadata)
class TorchMetadata: NSManagedObject {
static let NAME = "TorchSwift_TorchMetadata"
@NSManaged var torchEntityName: String
@NSManaged var lastAssignedId: NSNumber
static func describeEntity(to registry: EntityRegistry) {
let entity = NSEntityDescription()
entity.name = NAME
entity.managedObjectClassName = String(TorchMetadata)
let name = NSAttributeDescription()
name.name = "torchEntityName"
name.attributeType = .StringAttributeType
name.optional = false
let id = NSAttributeDescription()
id.name = "lastAssignedId"
id.attributeType = .Integer64AttributeType
id.optional = false
entity.properties = [name, id]
registry.describe(NAME, as: entity)
}
}
| mit | 81ef36f02b622f016686d046848a2e3a | 25.131579 | 61 | 0.652568 | 4.728571 | false | false | false | false |
alexito4/Error-Handling-Script-Rust-Swift | Pods/Swiftline/Pod/Swiftline/Runner/RunnerSettings.swift | 1 | 1276 | //
// RunSettings.swift
// RunSettings
//
// Created by Omar Abdelhafith on 05/11/2015.
// Copyright © 2015 Omar Abdelhafith. All rights reserved.
//
import Foundation
/// Settings to costumize the run function
public class RunSettings {
/// If set to true, the command wont be run on the system, the stdout will contain the command executed
public var dryRun = false
/// Which parts of the command to be echoed during execution
public var echo = EchoSettings.None
/// Run the command in interactive mode; output wont be captured
public var interactive = false
}
/// Echo settings
public struct EchoSettings: OptionSetType {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
/// Dont echo anything, this is the default settings
public static var None = EchoSettings(rawValue: 0)
/// Echo the stdout from the run command to the terminal
public static let Stdout = EchoSettings(rawValue: 1 << 0)
/// Echo the stderr from the run command to the terminal
public static let Stderr = EchoSettings(rawValue: 1 << 1)
/// Echo the command executed to the terminal
public static let Command = EchoSettings(rawValue: 1 << 2)
} | mit | 27259e5019967343ce74394a534a6e74 | 26.73913 | 107 | 0.680784 | 4.427083 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/ChatsControllers/InputContainerView+AttachDataSource.swift | 1 | 5480 | //
// InputContainerView+AttachDataSource.swift
// Pigeon-project
//
// Created by Roman Mizin on 8/20/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
import Photos
private let attachCollectionViewCellID = "attachCollectionViewCellID"
extension InputContainerView: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func configureAttachCollectionView() {
attachCollectionView.delegate = self
attachCollectionView.dataSource = self
attachCollectionView.register(AttachCollectionViewCell.self, forCellWithReuseIdentifier: attachCollectionViewCellID)
}
@objc func removeButtonDidTap(sender: UIButton) {
guard let cell = sender.superview as? AttachCollectionViewCell,
let indexPath = attachCollectionView.indexPath(for: cell) else { return }
let row = indexPath.row
guard let asset = attachedMedia[row].phAsset, let picker = mediaPickerController else {
attachedMedia.remove(at: row)
attachCollectionView.deleteItems(at: [indexPath])
resetChatInputConntainerViewSettings()
return
}
if picker.assets.contains(asset) {
deselectAsset(row: row)
} else {
attachedMedia.remove(at: row)
attachCollectionView.deleteItems(at: [indexPath])
resetChatInputConntainerViewSettings()
}
}
func deselectAsset(row: Int) {
guard let picker = mediaPickerController,
attachedMedia.indices.contains(row),
let asset = attachedMedia[row].phAsset,
let index = picker.assets.firstIndex(of: asset) else { return }
let indexPath = IndexPath(item: index, section: ImagePickerTrayController.librarySectionIndex)
picker.collectionView.deselectItem(at: indexPath, animated: true)
picker.delegate?.controller?(picker, didDeselectAsset: asset, at: indexPath)
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = attachCollectionView.dequeueReusableCell(withReuseIdentifier: attachCollectionViewCellID,
for: indexPath) as? AttachCollectionViewCell ?? AttachCollectionViewCell()
cell.chatInputContainerView = self
cell.isVideo = attachedMedia[indexPath.item].phAsset?.mediaType == .video
guard let image = self.attachedMedia[indexPath.item].object?.asUIImage else { // it is voice message
let data = attachedMedia[indexPath.row].audioObject!
let duration = getAudioDurationInHours(from: data)
cell.image.contentMode = .scaleAspectFit
cell.image.image = UIImage(named: "VoiceMemo")
cell.playerViewHeightAnchor.constant = 20
cell.playerView.timerLabel.text = duration
cell.playerView.startingTime = getAudioDurationInSeconds(from: data)!
cell.playerView.seconds = getAudioDurationInSeconds(from: data)!
return cell
}
cell.image.image = image
return cell
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return attachedMedia.count
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if attachedMedia[indexPath.item].audioObject != nil {
return
}
if attachedMedia[indexPath.item].phAsset?.mediaType == PHAssetMediaType.image || attachedMedia[indexPath.item].phAsset == nil {
chatLogController?.presentPhotoEditor(forImageAt: indexPath)
}
if attachedMedia[indexPath.item].phAsset?.mediaType == PHAssetMediaType.video {
chatLogController?.presentVideoPlayer(forUrlAt: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard attachedMedia.indices.contains(indexPath.row) else { return CGSize(width: 0, height: 0) }
guard attachedMedia[indexPath.row].audioObject != nil else {
let oldHeight = self.attachedMedia[indexPath.row].object?.asUIImage!.size.height
let scaleFactor = AttachCollectionView.cellHeight / oldHeight!
let newWidth = self.attachedMedia[indexPath.row].object!.asUIImage!.size.width * scaleFactor
let newHeight = oldHeight! * scaleFactor
return CGSize(width: newWidth, height: newHeight)
}
let oldHeight = UIImage(named: "VoiceMemo")!.size.height
let scaleFactor = AttachCollectionView.cellHeight / oldHeight
let newWidth = UIImage(named: "VoiceMemo")!.size.width * scaleFactor
let newHeight = oldHeight * scaleFactor
return CGSize(width: newWidth, height: newHeight)
}
private func getAudioDurationInHours(from data: Data) -> String? {
do {
audioPlayer = try AVAudioPlayer(data: data)
let duration = Int(audioPlayer!.duration)
let hours = Int(duration) / 3600
let minutes = Int(duration) / 60 % 60
let seconds = Int(duration) % 60
return String(format: "%02i:%02i:%02i", hours, minutes, seconds)
} catch {
print("error playing")
return String(format: "%02i:%02i:%02i", 0, 0, 0)
}
}
private func getAudioDurationInSeconds(from data: Data) -> Int? {
do {
audioPlayer = try AVAudioPlayer(data: data)
let duration = Int(audioPlayer!.duration)
return duration
} catch {
print("error playing")
return nil
}
}
}
| gpl-3.0 | fa7da9854de8374284e943fa84934827 | 36.272109 | 158 | 0.720752 | 4.666951 | false | false | false | false |
tschob/HSAudioPlayer | Example/Core/ViewController/SharedInstancePlayer/HSEMusicLibraryViewController.swift | 1 | 1432 | //
// HSEMusicLibraryViewController.swift
// Example
//
// Created by Hans Seiffert on 02.08.16.
// Copyright © 2016 Hans Seiffert. All rights reserved.
//
import UIKit
import HSAudioPlayer
import MediaPlayer
class HSEMusicLibraryViewController: UIViewController {
var data : [MPMediaItem] = []
override func viewDidLoad() {
super.viewDidLoad()
HSAudioPlayer.sharedInstance.setup()
let tempData = MPMediaQuery.songsQuery().items ?? []
self.data = []
for mediaItem in tempData {
if (mediaItem.cloudItem == false && mediaItem.assetURL != nil) {
self.data.append(mediaItem)
if (self.data.count >= 20) {
break
}
}
}
}
}
// MARK: - UITableView delegates
extension HSEMusicLibraryViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("musicLibraryCell", forIndexPath: indexPath)
cell.textLabel?.text = self.data[indexPath.row].title
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
HSAudioPlayer.sharedInstance.play(mediaItems: self.data, startPosition: indexPath.row)
}
}
| mit | 32b3f08cd0e43ebf354c3f0042a27323 | 25.5 | 106 | 0.749825 | 4.053824 | false | false | false | false |
imjerrybao/SocketIO-Kit | Source/SocketIOPayload.swift | 2 | 1482 | //
// SocketIOPayload.swift
// Smartime
//
// Created by Ricardo Pereira on 02/05/2015.
// Copyright (c) 2015 Ricardo Pereira. All rights reserved.
//
import Foundation
class SocketIOPayload {
static private func regEx() -> NSRegularExpression? {
// Regular Expression: <length>:<packet>, added 0 for parse optimization
//because packet as suffix 0 for string data
return NSRegularExpression(pattern: "^[0-9]{2,}:0", options: .CaseInsensitive, error: nil)
}
static func isStringPacket(payload: NSString) -> Bool {
if let regex = regEx() {
let all = NSMakeRange(0, payload.length)
// Check pattern
let matchPattern = regex.rangeOfFirstMatchInString(payload as String, options: .ReportProgress, range: all)
// Result
return matchPattern.location != NSNotFound
}
return false
}
static func getStringPacket(payload: NSString) -> String {
if let regex = regEx() {
let all = NSMakeRange(0, payload.length)
// Check pattern and get remaining part: packet
if let match = regex.firstMatchInString(payload as String, options: .ReportProgress, range: all) {
let packet = NSMakeRange(match.range.length, payload.length - match.range.length)
// Result: JSON
return payload.substringWithRange(packet)
}
}
return ""
}
} | mit | ff25ec86d646ef0de46c49ad4d0d55ea | 33.488372 | 119 | 0.611336 | 4.734824 | false | false | false | false |
ben-ng/swift | stdlib/public/SwiftOnoneSupport/SwiftOnoneSupport.swift | 1 | 4539 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// Pre-specialization of some popular generic classes and functions.
//===----------------------------------------------------------------------===//
import Swift
struct _Prespecialize {
// Create specializations for the arrays of most
// popular builtin integer and floating point types.
static internal func _specializeArrays() {
func _createArrayUser<Element : Comparable>(_ sampleValue: Element) {
// Initializers.
let _: [Element] = [sampleValue]
var a = [Element](repeating: sampleValue, count: 1)
// Read array element
let _ = a[0]
// Set array elements
for j in 1..<a.count {
a[0] = a[j]
a[j-1] = a[j]
}
for i1 in 0..<a.count {
for i2 in 0..<a.count {
a[i1] = a[i2]
}
}
a[0] = sampleValue
// Get count and capacity
let _ = a.count + a.capacity
// Iterate over array
for e in a {
print(e)
print("Value: \(e)")
}
print(a)
// Reserve capacity
a.removeAll()
a.reserveCapacity(100)
// Sort array
let _ = a.sorted { (a: Element, b: Element) in a < b }
a.sort { (a: Element, b: Element) in a < b }
// force specialization of append.
a.append(a[0])
// force specialization of print<Element>
print(sampleValue)
print("Element:\(sampleValue)")
}
func _createArrayUserWithoutSorting<Element>(_ sampleValue: Element) {
// Initializers.
let _: [Element] = [sampleValue]
var a = [Element](repeating: sampleValue, count: 1)
// Read array element
let _ = a[0]
// Set array elements
for j in 0..<a.count {
a[0] = a[j]
}
for i1 in 0..<a.count {
for i2 in 0..<a.count {
a[i1] = a[i2]
}
}
a[0] = sampleValue
// Get length and capacity
let _ = a.count + a.capacity
// Iterate over array
for e in a {
print(e)
print("Value: \(e)")
}
print(a)
// Reserve capacity
a.removeAll()
a.reserveCapacity(100)
// force specialization of append.
a.append(a[0])
// force specialization of print<Element>
print(sampleValue)
print("Element:\(sampleValue)")
}
// Force pre-specialization of arrays with elements of different
// integer types.
_createArrayUser(1 as Int)
_createArrayUser(1 as Int8)
_createArrayUser(1 as Int16)
_createArrayUser(1 as Int32)
_createArrayUser(1 as Int64)
_createArrayUser(1 as UInt)
_createArrayUser(1 as UInt8)
_createArrayUser(1 as UInt16)
_createArrayUser(1 as UInt32)
_createArrayUser(1 as UInt64)
// Force pre-specialization of arrays with elements of different
// floating point types.
_createArrayUser(1.5 as Float)
_createArrayUser(1.5 as Double)
// Force pre-specialization of string arrays
_createArrayUser("a" as String)
// Force pre-specialization of arrays with elements of different
// character and unicode scalar types.
_createArrayUser("a" as Character)
_createArrayUser("a" as UnicodeScalar)
_createArrayUserWithoutSorting("a".utf8)
_createArrayUserWithoutSorting("a".utf16)
_createArrayUserWithoutSorting("a".unicodeScalars)
_createArrayUserWithoutSorting("a".characters)
}
// Force pre-specialization of Range<Int>
@discardableResult
static internal func _specializeRanges() -> Int {
let a = [Int](repeating: 1, count: 10)
var count = 0
// Specialize Range for integers
for i in 0..<a.count {
count += a[i]
}
// Specialize Range for integers
for j in 0...a.count - 1{
count += a[j]
}
return count
}
}
// Mark with optimize.sil.never to make sure its not get
// rid of by dead function elimination.
@_semantics("optimize.sil.never")
internal func _swift_forcePrespecializations() {
_Prespecialize._specializeArrays()
_Prespecialize._specializeRanges()
}
| apache-2.0 | a6622a2998eb9c744533c4077acd162c | 26.017857 | 80 | 0.583388 | 4.257974 | false | false | false | false |
Wzxhaha/WZXDataManager | Sources/Table.swift | 1 | 3811 | //
// Table.swift
// NoDB
//
// Created by WzxJiang on 17/5/16.
// Copyright © 2016年 WzxJiang. All rights reserved.
//
// https://github.com/Wzxhaha/NoDB
//
// 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 protocol Tableable: class {
static var name: String { get }
var propertys: [Property] { get }
// I want to give a id to model when it's fetched
// this id will help us to update current model.
var _id: Int? { set get }
init(_ dictionary: [String: Any?])
}
extension Tableable {
var values: [Any]? {
return propertys.flatMap { $0._value }
}
}
extension Tableable {
internal var createSQL: String {
var sql = "CREATE TABLE IF NOT EXISTS \(Self.name)"
sql += "("
sql += "_id INTEGER PRIMARY KEY AUTOINCREMENT"
propertys.forEach {
sql += ","
sql += "\($0.key) \($0.type.sql.rawValue)"
}
sql += ")"
return sql
}
internal var insertSQL: String {
var sql = "INSERT INTO \(Self.name)"
sql += propertys.reduce("(", { $0 + $1.key + ","})
sql.remove(at: sql.index(before: sql.endIndex))
sql += ") "
sql += "VALUES(\("?," * propertys.count)"
sql.remove(at: sql.index(before: sql.endIndex))
sql += ")"
return sql
}
internal var fetchSQL: String {
let baseSQL = "SELECT * FROM \(Self.name)"
return equalSQL(withBase: baseSQL, lastKey: " WHERE ")
}
internal var deleteSQL: String {
let baseSQL = "DELETE FROM \(Self.name)"
return equalSQL(withBase: baseSQL, lastKey: " WHERE ")
}
internal var updateSQL: String {
let baseSQL = "UPDATE \(Self.name)"
guard let id = _id else {
return baseSQL
}
return equalSQL(withBase: baseSQL, lastKey: " SET ") + " WHERE _id=\(id)"
}
private func equalSQL(withBase base: String, lastKey: String) -> String {
var sql = base + lastKey
propertys.forEach {
if $0.value != nil {
sql += $0.key
sql += "=? AND "
}
}
if (base + lastKey).utf8.count == sql.utf8.count {
sql.removeSubrange(sql.index(sql.endIndex, offsetBy: -(lastKey.utf8.count))..<sql.endIndex)
} else {
sql.removeSubrange(sql.index(sql.endIndex, offsetBy: -(" AND ".utf8.count))..<sql.endIndex)
}
return sql
}
}
private func *(lhs: String, rhs: Int) -> String {
var str = ""
for _ in 0..<rhs {
str += lhs
}
return str
}
| mit | f727d611f7eb6ed8ed6a5dbd75854cb0 | 28.068702 | 103 | 0.581408 | 4.085837 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/UpdateIntent.swift | 2 | 2158 | /**
* Copyright IBM Corporation 2018
*
* 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
/** UpdateIntent. */
public struct UpdateIntent: Encodable {
/// The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters.
public var intent: String?
/// The description of the intent.
public var description: String?
/// An array of user input examples for the intent.
public var examples: [CreateExample]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case intent = "intent"
case description = "description"
case examples = "examples"
}
/**
Initialize a `UpdateIntent` with member variables.
- parameter intent: The name of the intent. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, hyphen, and dot characters. - It cannot begin with the reserved prefix `sys-`. - It must be no longer than 128 characters.
- parameter description: The description of the intent.
- parameter examples: An array of user input examples for the intent.
- returns: An initialized `UpdateIntent`.
*/
public init(intent: String? = nil, description: String? = nil, examples: [CreateExample]? = nil) {
self.intent = intent
self.description = description
self.examples = examples
}
}
| mit | e2be326fec1a04e47b1d3d9657d0aabd | 39.716981 | 286 | 0.7076 | 4.562368 | false | false | false | false |
Mathpix/ios-client | MathpixClient/Classes/Camera/MathCaptureViewController.swift | 1 | 17008 | //
// CameraSessionController.swift
// MathPix
//
// Created by Michael Lee on 3/25/16.
// Copyright © 2016 MathPix. All rights reserved.
//
import Foundation
import UIKit
/**
* This class is the top-level of the app UI, and
* is responsible for handling navigation between the camera and result views.
*/
open class MathCaptureViewController: UIViewController
{
/// Callback called after onBack method invoked.
public var backButtonCallback : MathpixClient.BackButtonCallback?
/// Callback called after recognition process completed.
public var completionCallback : MathpixClient.RecognitionCallback?
/// Formats that the mathpix server should represent in response.
public var outputFormats : [MathpixFormat]?
/// UI/UX properties to MathCaptureViewController.
public var properties : MathCaptureProperties!
/// Animation recognition delegate
public weak var delegate: MathCaptureViewControllerRecognitionAnimationDelegate?
/// Callback called when crop area selected
public var regionSelectedCallback: (()->())?
/// Callback called when crop area start dragging
public var regionDraggingBeganCallback: (()->())?
/// Callback called when crop area dragging
public var regionDraggingCallback: ((_ bottomCenter : CGPoint)->())?
fileprivate var cropOverlay : CropControlOverlay!
fileprivate var cameraView = MPCameraSessionView(forAutoLayout: ())
fileprivate var dimmingView : UIView?
fileprivate let tapActionView = UIView(forAutoLayout: ())
fileprivate var flashButton : UIButton = MPCameraFlashButton(forAutoLayout: ())
fileprivate var shutterButton = UIButton(forAutoLayout: ())
fileprivate var backButton = UIButton(forAutoLayout: ())
fileprivate var infoTopConstraint: NSLayoutConstraint!
fileprivate var cropInfoLabel = UILabel(forAutoLayout: ())
fileprivate var animator: RecognitionAnimator!
fileprivate var currentRequestId : UUID?
override open var shouldAutorotate : Bool {
return false
}
override open var supportedInterfaceOrientations : UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}
override open func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.clear
setupProperties()
setupCamera()
switch properties.captureType {
case .button:
setupShutterButton()
case .gesture:
setupLabels()
setupGestures()
}
for button in properties.requiredButtons {
switch button {
case .back:
setupBackButton()
case .flash:
setupFlashButton()
}
}
setupOverlay()
setupOverlayCallbacks()
setupDimmingView()
}
override open func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
cropOverlay.resetView()
self.setStatusBarStyle()
}
// MARK: - SETUP METHODS
// Setup overlay view with crop area
fileprivate func setupOverlay(){
cropOverlay = CropControlOverlay(color: properties.cropColor)
view.addSubview(cropOverlay)
cropOverlay.autoPinEdgesToSuperviewEdges(with: properties.cropAreaInsets)
cropOverlay.isResultViewActive = true
animator = properties.animatorType.init()
}
// Setup callbacks to crop area events
fileprivate func setupOverlayCallbacks() {
cropOverlay.draggingCallback = { [unowned self] bottomCenter in
let convertedPoint = self.view.convert(bottomCenter, from: self.cropOverlay)
self.infoTopConstraint?.constant = convertedPoint.y + 20
self.regionDraggingCallback?(convertedPoint)
}
cropOverlay.draggingBeganCallback = { [unowned self] in
self.regionDraggingBeganCallback?()
}
cropOverlay.regionSelectedCallback = { [unowned self] in
self.regionSelectedCallback?()
}
}
// Setup help info label
fileprivate func setupLabels() {
cropInfoLabel.text = NSLocalizedString("Tap info label text", comment: "")
cropInfoLabel.textColor = UIColor.white
cropInfoLabel.font = UIFont.systemFont(ofSize: 20)
cropInfoLabel.adjustsFontSizeToFitWidth = true
cropInfoLabel.minimumScaleFactor = 0.6
cropInfoLabel.numberOfLines = 1
cropInfoLabel.textAlignment = .center
view.addSubview(cropInfoLabel)
cropInfoLabel.autoPinEdge(toSuperviewEdge: .leading, withInset: 10)
cropInfoLabel.autoPinEdge(toSuperviewEdge: .trailing, withInset: 10)
infoTopConstraint = cropInfoLabel.autoPinEdge(toSuperviewEdge: .top, withInset: 0)
}
// Setup tap gesture to capture image
fileprivate func setupGestures() {
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(MathCaptureViewController.onCapture))
tapActionView.addGestureRecognizer(tapGesture)
tapActionView.backgroundColor = UIColor.clear
view.addSubview(tapActionView)
tapActionView.autoPinEdgesToSuperviewEdges()
}
// Setup camera view
fileprivate func setupCamera() {
self.view.addSubview(cameraView)
self.cameraView.autoPinEdgesToSuperviewEdges()
self.cameraView.delegate = self
self.cameraView.hideCameraToogleButton()
DispatchQueue.main.async {
self.cameraView.hideFlashButton()
}
}
// Setup flash button
fileprivate func setupFlashButton() {
if let flashIcon = properties.flashIcon {
flashButton = UIButton(forAutoLayout: ())
flashButton.setImage(flashIcon, for: .normal)
flashButton.contentVerticalAlignment = .fill
flashButton.contentHorizontalAlignment = .fill
} else {
let color = self.view.tintColor
flashButton.layer.borderWidth = 1.5
flashButton.layer.borderColor = color!.cgColor
flashButton.layer.cornerRadius = properties.smallButtonSize.height / 2.0
flashButton.layer.masksToBounds = true
}
flashButton.addTarget(self, action: #selector(MathCaptureViewController.onFlash), for: .touchUpInside)
view.addSubview(flashButton)
flashButton.autoPinEdge(toSuperviewEdge: .leading, withInset: 20)
flashButton.autoPin(toTopLayoutGuideOf: self, withInset: 8)
flashButton.autoSetDimensions(to: properties.smallButtonSize)
}
// Setup shutter button
fileprivate func setupShutterButton() {
shutterButton.setImage(properties.shutterIcon, for: .normal)
shutterButton.contentVerticalAlignment = .fill
shutterButton.contentHorizontalAlignment = .fill
shutterButton.addTarget(self, action: #selector(MathCaptureViewController.onCapture), for: .touchUpInside)
view.addSubview(shutterButton)
shutterButton.autoPin(toBottomLayoutGuideOf: self, withInset: 20)
shutterButton.autoAlignAxis(toSuperviewAxis: .vertical)
shutterButton.autoSetDimensions(to: properties.bigButtonSize)
}
// Setup back button
fileprivate func setupBackButton() {
backButton.setImage(properties.backIcon, for: .normal)
backButton.contentVerticalAlignment = .fill
backButton.contentHorizontalAlignment = .fill
backButton.addTarget(self, action: #selector(MathCaptureViewController.onBack), for: .touchUpInside)
view.addSubview(backButton)
backButton.autoPin(toBottomLayoutGuideOf: self, withInset: 20)
backButton.autoPinEdge(toSuperviewEdge: .leading, withInset: 20)
backButton.autoSetDimensions(to: properties.smallButtonSize)
}
/**
* This method called before viewDidLoad. Override it to set custom properties value. Do not call super.
*/
open func setupProperties() {
properties = properties ?? MathCaptureProperties()
}
/**
* Set status bar style. Override if need change it.
*/
open func setStatusBarStyle() {
UIApplication.shared.setStatusBarStyle(.lightContent, animated: true)
}
/**
* This method set dimming view, which used when recognition process is active. Override this method to set yuor own dimming view. You can control it behavior via MathCaptureViewControllerRecognitionAnimationDelegate methods
*/
open func setupDimmingView() {
dimmingView = UIView(forAutoLayout: ())
dimmingView?.backgroundColor = UIColor.clear
dimmingView?.isHidden = true
view.insertSubview(dimmingView!, belowSubview: cropOverlay)
self.dimmingView?.autoPinEdge(.leading, to: .leading, of: view)
self.dimmingView?.autoPinEdge(.trailing, to: .trailing, of: view)
self.dimmingView?.autoPinEdge(.top, to: .top, of: view)
self.dimmingView?.autoPin(toBottomLayoutGuideOf: self, withInset: 0)
let cancelButton = UIButton()
cancelButton.setImage(properties.cancelIcon, for: .normal)
cancelButton.contentVerticalAlignment = .fill
cancelButton.contentHorizontalAlignment = .fill
cancelButton.addTarget(self, action: #selector(MathCaptureViewController.onCancel), for: .touchUpInside)
dimmingView?.addSubview(cancelButton)
cancelButton.autoPinEdge(toSuperviewEdge: .bottom, withInset: 20)
cancelButton.autoAlignAxis(toSuperviewAxis: .vertical)
cancelButton.autoSetDimensions(to: properties.smallButtonSize)
}
// MARK: - Actions
/// Turn on torch on camera.
public func onFlash() {
self.cameraView.onTapFlashButton()
}
/// This method capture image when invoked.
public func onCapture() {
changeControlsState(isEnabled: false)
self.cropOverlay.flashCrop()
self.cameraView.onTapShutterButton()
self.animate(shutterButton)
// Test in simulator
// self.captureOnSimulator()
}
/// Cancel recognition process
public func onCancel() {
changeControlsState(isEnabled: true)
if let id = currentRequestId {
MathpixClient.cancelRequest(id)
}
}
/// Dismiss current controller
public func onBack() {
backButtonCallback?()
self.dismiss(animated: true)
}
/// Display error under crop area. This method is async. Error will be presented eventually.
public func onDisplayErrorEventually(_ error: Error) {
cropOverlay.displayErrorEventually(error)
}
// MARK: - Overriding methods
/**
* This method called after recognition process is finished.
* - Parameter error: Error object if recognition failed.
* - Parameter result: RecognitionResult object if recognition succesed.
*/
open func didRecieve(error: Error?, result: RecognitionResult?) {
}
/**
* This method change state of controls to enabled or disabled when capture/recognize process happens. You can ovveride this method to change your own controls state.
* - Parameter isEnabled: Bool value indicate what state of controlls need to be set.
*/
open func controlStateChanged(isEnabled: Bool) {
}
// Helpers
fileprivate func captureOnSimulator() {
#if arch(i386) || arch(x86_64)
self.didCapture(MathpixClient.getImageFromResourceBundle(name: "equation")!)
#endif
}
fileprivate func changeControlsState(isEnabled: Bool) {
flashButton.isEnabled = isEnabled
shutterButton.isEnabled = isEnabled
backButton.isEnabled = isEnabled
tapActionView.gestureRecognizers?.forEach{ $0.isEnabled = isEnabled }
cropOverlay.cropControl.isUserInteractionEnabled = isEnabled
controlStateChanged(isEnabled: isEnabled)
}
// MARK: - Animations
fileprivate let animationScaleTransformMultiplier : CGFloat = 1.8
fileprivate let animationDuration = 0.27
func animate(_ button: UIButton) {
UIView.animateKeyframes(withDuration: animationDuration, delay: 0, options: [], animations: {
UIView.animateKeyframes(withDuration: 0.5, delay: 0, options: [], animations: {
button.transform = CGAffineTransform(scaleX: self.animationScaleTransformMultiplier, y: self.animationScaleTransformMultiplier)
}, completion: nil)
UIView.animateKeyframes(withDuration: 0.5, delay: 0, options: [], animations: {
button.transform = CGAffineTransform.identity
}, completion: nil)
}, completion: nil)
}
func startAnimateRecognition() {
// Notify delegate
self.delegate?.willStartAnimateRecognition?()
// Show dimming view
dimmingView?.alpha = 0.0
dimmingView?.isHidden = false
dimmingView?.backgroundColor = UIColor(white: 0.1, alpha: 0.8)
// begin recognition animation
self.cropOverlay.addSubview(animator.view)
animator.view.autoCenterInSuperview()
self.animator.beginAnimation()
UIView.animate(withDuration: 0.4, animations: {
self.dimmingView?.alpha = 1.0
// Hide other controls
self.cropInfoLabel.isHidden = true
self.flashButton.isHidden = true
self.shutterButton.isHidden = true
self.backButton.isHidden = true
}) { (finished) in
// Notify delegate
self.delegate?.didStartAnimateRecognition?()
}
}
func stopAnimateRecognition(completionBlock: (() -> ())? = nil) {
// Notify delegate
self.delegate?.willEndAnimateRecognition?()
// finish recognition animation
self.animator.finishAnimation()
self.animator.view.removeFromSuperview()
UIView.animate(withDuration: 0.4, animations: {
// Hide dimming view
self.dimmingView?.alpha = 0.0
}) { (finished) in
self.dimmingView?.isHidden = true
// Return other controls
self.cropInfoLabel.isHidden = false
self.flashButton.isHidden = false
self.shutterButton.isHidden = false
self.backButton.isHidden = false
completionBlock?()
// Clear crop area
self.cropOverlay.clearResultView(animated: true)
// Notify delegate
self.delegate?.didEndAnimateRecognition?()
}
}
}
extension MathCaptureViewController: MPCameraSessionDelegate {
open func didFailCaptureWithError(_ error: Error!) {
changeControlsState(isEnabled: true)
completionCallback?(error, nil)
MathpixClient.completion?(error, nil)
self.didRecieve(error: error, result: nil)
var handled = false
if let error = error, self.properties.errorHandling == true {
handled = true
self.handle(error)
}
// Exit if completion not nil and error not handled internal
if self.completionCallback != nil && !handled {
self.dismiss(animated: true)
}
}
open func didCapture(_ image: UIImage!) {
if let resultImage = RecognitionService.cropImage(image, bounds: cameraView.bounds) {
let croppedImage = cropOverlay.cropImageAndUpdateDisplay(resultImage, superview: cameraView)
self.startAnimateRecognition()
self.currentRequestId = MathpixClient.recognize(image: croppedImage, outputFormats: outputFormats, completion: { [weak self] (error, result) in
self?.currentRequestId = nil
self?.stopAnimateRecognition()
self?.changeControlsState(isEnabled: true)
// we don't need exit if user cancel request, catch request canceled error
if let error = error as? NetworkError, error == .requestCanceled {
return
}
self?.completionCallback?(error, result)
MathpixClient.completion?(error, result)
self?.didRecieve(error: error, result: result)
var handled = false
if let error = error, self?.properties.errorHandling == true {
handled = true
self?.handle(error)
}
// Exit if completion not nil and error not handled internal
if self?.completionCallback != nil && !handled {
self?.dismiss(animated: true)
}
})
}
}
}
| mit | a3d1b4244f08ca8c6b3a54354d5566cd | 34.728992 | 229 | 0.648498 | 5.378558 | false | false | false | false |
pbernery/R.swift | R.swift/func.swift | 2 | 12677 | //
// func.swift
// R.swift
//
// Created by Mathijs Kadijk on 14-12-14.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
import Foundation
// MARK: Helper functions
let indent = indentWithString(IndentationString)
func warn(warning: String) {
print("warning: [R.swift] \(warning)")
}
func fail(error: String) {
print("error: [R.swift] \(error)")
}
func fail<T: ErrorType where T: CustomStringConvertible>(error: T) {
fail("\(error)")
}
func filterDirectoryContentsRecursively(fileManager: NSFileManager, filter: (NSURL) -> Bool)(url: NSURL) -> [NSURL] {
var assetFolders = [NSURL]()
let errorHandler: (NSURL!, NSError!) -> Bool = { url, error in
fail(error)
return true
}
if let enumerator = fileManager.enumeratorAtURL(url, includingPropertiesForKeys: [NSURLIsDirectoryKey], options: [NSDirectoryEnumerationOptions.SkipsHiddenFiles, NSDirectoryEnumerationOptions.SkipsPackageDescendants], errorHandler: errorHandler) {
while let enumeratorItem: AnyObject = enumerator.nextObject() {
if let url = enumeratorItem as? NSURL where filter(url) {
assetFolders.append(url)
}
}
}
return assetFolders
}
func sanitizedSwiftName(name: String, lowercaseFirstCharacter: Bool = true) -> String {
var components = name.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " -.@"))
let firstComponent = components.removeAtIndex(0)
let swiftName = components.reduce(firstComponent) { $0 + $1.capitalizedString }
let capitalizedSwiftName = lowercaseFirstCharacter ? swiftName.lowercaseFirstCharacter : swiftName
return SwiftKeywords.contains(capitalizedSwiftName) ? "`\(capitalizedSwiftName)`" : capitalizedSwiftName
}
func writeResourceFile(code: String, toFileURL fileURL: NSURL) {
do {
try code.writeToURL(fileURL, atomically: true, encoding: NSUTF8StringEncoding)
} catch let error as NSError {
fail(error)
}
}
func readResourceFile(fileURL: NSURL) -> String? {
do {
return try String(contentsOfURL: fileURL, encoding: NSUTF8StringEncoding)
} catch {
return nil
}
}
// MARK: Struct/function generators
// Image
func imageStructFromAssetFolders(assetFolders: [AssetFolder], andImages images: [Image]) -> Struct {
let assetFolderImageVars = assetFolders
.flatMap { $0.imageAssets }
.map { Var(isStatic: true, name: $0, type: Type._UIImage.asOptional(), getter: "return UIImage(named: \"\($0)\")") }
let uniqueImages = images
.groupBy { $0.name }
.values
.flatMap { $0.first }
let imageVars = uniqueImages
.map { Var(isStatic: true, name: $0.name, type: Type._UIImage.asOptional(), getter: "return UIImage(named: \"\($0.name)\")") }
let vars = (assetFolderImageVars + imageVars)
.groupUniquesAndDuplicates { $0.callName }
for duplicate in vars.duplicates {
let names = duplicate.map { $0.name }.sort().joinWithSeparator(", ")
warn("Skipping \(duplicate.count) images because symbol '\(duplicate.first!.callName)' would be generated for all of these images: \(names)")
}
return Struct(type: Type(name: "image"), lets: [], vars: vars.uniques, functions: [], structs: [])
}
// Segue
func segueStructFromStoryboards(storyboards: [Storyboard]) -> Struct {
let vars = Array(Set(storyboards.flatMap { $0.segues }))
.map { Var(isStatic: true, name: $0, type: Type._String, getter: "return \"\($0)\"") }
return Struct(type: Type(name: "segue"), lets: [], vars: vars, functions: [], structs: [])
}
// Storyboard
func storyboardStructAndFunctionFromStoryboards(storyboards: [Storyboard]) -> (Struct, Function) {
let groupedStoryboards = storyboards.groupUniquesAndDuplicates { sanitizedSwiftName($0.name) }
for duplicate in groupedStoryboards.duplicates {
let names = duplicate.map { $0.name }.sort().joinWithSeparator(", ")
warn("Skipping \(duplicate.count) storyboards because symbol '\(sanitizedSwiftName(duplicate.first!.name))' would be generated for all of these storyboards: \(names)")
}
return (
Struct(type: Type(name: "storyboard"), lets: [], vars: [], functions: [], structs: groupedStoryboards.uniques.map(storyboardStructForStoryboard)),
validateAllFunctionWithStoryboards(groupedStoryboards.uniques)
)
}
func storyboardStructForStoryboard(storyboard: Storyboard) -> Struct {
let instanceVars = [Var(isStatic: true, name: "instance", type: Type._UIStoryboard, getter: "return UIStoryboard(name: \"\(storyboard.name)\", bundle: nil)")]
let initialViewControllerVar = [storyboard.initialViewController
.map { (vc) -> Var in
let getterCast = (vc.type.asNonOptional() == Type._UIViewController) ? "" : " as? \(vc.type.asNonOptional())"
return Var(isStatic: true, name: "initialViewController", type: vc.type.asOptional(), getter: "return instance.instantiateInitialViewController()\(getterCast)")
}
].flatMap { $0 }
let viewControllerVars = storyboard.viewControllers
.flatMap { (vc) -> Var? in
let getterCast = (vc.type.asNonOptional() == Type._UIViewController) ? "" : " as? \(vc.type.asNonOptional())"
return vc.storyboardIdentifier.map {
return Var(isStatic: true, name: $0, type: vc.type.asOptional(), getter: "return instance.instantiateViewControllerWithIdentifier(\"\($0)\")\(getterCast)")
}
}
let validateImagesLines = Array(Set(storyboard.usedImageIdentifiers))
.map { "assert(UIImage(named: \"\($0)\") != nil, \"[R.swift] Image named '\($0)' is used in storyboard '\(storyboard.name)', but couldn't be loaded.\")" }
let validateImagesFunc = Function(isStatic: true, name: "validateImages", generics: nil, parameters: [], returnType: Type._Void, body: validateImagesLines.joinWithSeparator("\n"))
let validateViewControllersLines = storyboard.viewControllers
.flatMap { vc in
vc.storyboardIdentifier.map {
"assert(\(sanitizedSwiftName($0)) != nil, \"[R.swift] ViewController with identifier '\(sanitizedSwiftName($0))' could not be loaded from storyboard '\(storyboard.name)' as '\(vc.type)'.\")"
}
}
let validateViewControllersFunc = Function(isStatic: true, name: "validateViewControllers", generics: nil, parameters: [], returnType: Type._Void, body: validateViewControllersLines.joinWithSeparator("\n"))
return Struct(type: Type(name: sanitizedSwiftName(storyboard.name)), lets: [], vars: instanceVars + initialViewControllerVar + viewControllerVars, functions: [validateImagesFunc, validateViewControllersFunc], structs: [])
}
func validateAllFunctionWithStoryboards(storyboards: [Storyboard]) -> Function {
return Function(isStatic: true, name: "validate", generics: nil, parameters: [], returnType: Type._Void, body: storyboards.map(swiftCallStoryboardValidators).joinWithSeparator("\n"))
}
func swiftCallStoryboardValidators(storyboard: Storyboard) -> String {
return
"storyboard.\(sanitizedSwiftName(storyboard.name)).validateImages()\n" +
"storyboard.\(sanitizedSwiftName(storyboard.name)).validateViewControllers()"
}
// Nib
func nibStructFromNibs(nibs: [Nib]) -> (intern: Struct, extern: Struct) {
let groupedNibs = nibs.groupUniquesAndDuplicates { sanitizedSwiftName($0.name) }
for duplicate in groupedNibs.duplicates {
let names = duplicate.map { $0.name }.sort().joinWithSeparator(", ")
warn("Skipping \(duplicate.count) xibs because symbol '\(sanitizedSwiftName(duplicate.first!.name))' would be generated for all of these xibs: \(names)")
}
return (
intern: Struct(type: Type(name: "nib"), lets: [], vars: [], functions: [], structs: groupedNibs.uniques.map(nibStructForNib)),
extern: Struct(type: Type(name: "nib"), lets: [], vars: groupedNibs.uniques.map(nibVarForNib), functions: [], structs: [])
)
}
func nibVarForNib(nib: Nib) -> Var {
let nibStructName = sanitizedSwiftName("_\(nib.name)")
let structType = Type(name: "_R.nib.\(nibStructName)")
return Var(isStatic: true, name: nib.name, type: structType, getter: "return \(structType)()")
}
func nibStructForNib(nib: Nib) -> Struct {
let instantiateParameters = [
Function.Parameter(name: "ownerOrNil", type: Type._AnyObject.asOptional()),
Function.Parameter(name: "options", localName: "optionsOrNil", type: Type(name: "[NSObject : AnyObject]", optional: true))
]
let nameVar = Var(
isStatic: false,
name: "name",
type: Type._String,
getter: "return \"\(nib.name)\""
)
let instanceVar = Var(
isStatic: false,
name: "instance",
type: Type._UINib,
getter: "return UINib.init(nibName: \"\(nib.name)\", bundle: nil)"
)
let instantiateFunc = Function(
isStatic: false,
name: "instantiateWithOwner",
generics: nil,
parameters: instantiateParameters,
returnType: Type(name: "[AnyObject]"),
body: "return instance.instantiateWithOwner(ownerOrNil, options: optionsOrNil)"
)
let viewFuncs = zip(nib.rootViews, Ordinals)
.map { (view: $0.0, ordinal: $0.1) }
.map {
Function(
isStatic: false,
name: "\($0.ordinal.word)View",
generics: nil,
parameters: instantiateParameters,
returnType: $0.view.asOptional(),
body: "return \(instantiateFunc.callName)(ownerOrNil, options: optionsOrNil)[\($0.ordinal.number - 1)] as? \($0.view)"
)
}
let reuseIdentifierVars: [Var]
let reuseProtocols: [Type]
if let reusable = nib.reusables.first where nib.rootViews.count == 1 && nib.reusables.count == 1 {
let reusableVar = varFromReusable(reusable)
reuseIdentifierVars = [Var(
isStatic: false,
name: "reuseIdentifier",
type: reusableVar.type,
getter: reusableVar.getter
)]
reuseProtocols = [ReusableProtocol.type]
} else {
reuseIdentifierVars = []
reuseProtocols = []
}
let sanitizedName = sanitizedSwiftName(nib.name, lowercaseFirstCharacter: false)
return Struct(
type: Type(name: "_\(sanitizedName)"),
implements: [NibResourceProtocol.type] + reuseProtocols,
lets: [],
vars: [nameVar, instanceVar] + reuseIdentifierVars,
functions: [instantiateFunc] + viewFuncs,
structs: []
)
}
// Reuse identifiers
func reuseIdentifierStructFromReusables(reusables: [Reusable]) -> Struct {
let groupedReusables = reusables.groupUniquesAndDuplicates { sanitizedSwiftName($0.identifier) }
for duplicate in groupedReusables.duplicates {
let names = duplicate.map { $0.identifier }.sort().joinWithSeparator(", ")
warn("Skipping \(duplicate.count) reuseIdentifiers because symbol '\(sanitizedSwiftName(duplicate.first!.identifier))' would be generated for all of these reuseIdentifiers: \(names)")
}
let reuseIdentifierVars = groupedReusables
.uniques
.map(varFromReusable)
return Struct(type: Type(name: "reuseIdentifier"), lets: [], vars: reuseIdentifierVars, functions: [], structs: [])
}
func varFromReusable(reusable: Reusable) -> Var {
return Var(
isStatic: true,
name: reusable.identifier,
type: ReuseIdentifier.type.withGenericType(reusable.type),
getter: "return \(ReuseIdentifier.type.name)(identifier: \"\(reusable.identifier)\")"
)
}
// Fonts
func fontStructFromFonts(fonts: [Font]) -> Struct {
return Struct(type: Type(name: "font"), lets: [], vars: [], functions: fonts.map(fontFunctionFromFont), structs: [])
}
func fontFunctionFromFont(font: Font) -> Function {
return Function(
isStatic: true,
name: font.name,
generics: nil,
parameters: [
Function.Parameter(name: "size", localName: "size", type: Type._CGFloat)
],
returnType: Type._UIFont.asOptional(),
body:"return UIFont(name: \"\(font.name)\", size: size)"
)
}
// Resource files
func resourceStructFromResourceFiles(resourceFiles: [ResourceFile]) -> Struct {
let groupedResourceFiles = resourceFiles.groupUniquesAndDuplicates { sanitizedSwiftName($0.fullname) }
for duplicate in groupedResourceFiles.duplicates {
let names = duplicate.map { $0.fullname }.sort().joinWithSeparator(", ")
warn("Skipping \(duplicate.count) resource files because symbol '\(sanitizedSwiftName(duplicate.first!.fullname))' would be generated for all of these files: \(names)")
}
let resourceVars = groupedResourceFiles
.uniques
.map(varFromResourceFile)
return Struct(type: Type(name: "file"), lets: [], vars: resourceVars, functions: [], structs: [])
}
func varFromResourceFile(resourceFile: ResourceFile) -> Var {
let pathExtensionOrNilString = resourceFile.pathExtension ?? "nil"
return Var(isStatic: true, name: resourceFile.fullname, type: Type._NSURL.asOptional(), getter: "return NSBundle.mainBundle().URLForResource(\"\(resourceFile.filename)\", withExtension: \"\(pathExtensionOrNilString)\")")
}
| mit | 44280b0b2e98298870ddd37977b7166c | 37.767584 | 249 | 0.703952 | 4.095961 | false | false | false | false |
benjaminsnorris/CloudKitReactor | Sources/FetchCloudKitRecord.swift | 1 | 2100 | /*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import Foundation
import Reactor
import CloudKit
public struct FetchCloudKitRecord<T: CloudKitSyncable, U: State>: Command {
public var record: T
public var completion: (() -> Void)?
public var databaseScope: CKDatabase.Scope
public init(for record: T, databaseScope: CKDatabase.Scope = .private, completion: (() -> Void)? = nil) {
self.record = record
self.databaseScope = databaseScope
self.completion = completion
}
public func execute(state: U, core: Core<U>) {
let container = CKContainer.default()
switch databaseScope {
case .private:
container.privateCloudDatabase.fetch(withRecordID: record.cloudKitRecordID) { record, error in
self.process(record, error: error, state: state, core: core)
}
case .shared:
container.sharedCloudDatabase.fetch(withRecordID: record.cloudKitRecordID) { record, error in
self.process(record, error: error, state: state, core: core)
}
case .public:
container.publicCloudDatabase.fetch(withRecordID: record.cloudKitRecordID) { record, error in
self.process(record, error: error, state: state, core: core)
}
@unknown default:
fatalError()
}
}
private func process(_ record: CKRecord?, error: Error?, state: U, core: Core<U>) {
defer { completion?() }
if let error = error {
core.fire(event: CloudKitRecordFetchError(error: error))
} else if let record = record {
do {
let object = try T(record: record)
core.fire(event: CloudKitUpdated(object))
} catch {
core.fire(event: CloudKitRecordError(error, for: record))
}
} else {
core.fire(event: CloudKitRecordFetchError(error: CloudKitFetchError.unknown))
}
}
}
| mit | 87363e5b83f994c80cab3d99658ccab5 | 33.5 | 109 | 0.566184 | 4.451613 | false | false | false | false |
srn214/Floral | Floral/Pods/SwiftLocation/Sources/Locating By IP/LocationByIPRequest.swift | 1 | 2483 | //
// SwiftLocation - Efficient Location Tracking for iOS
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
import Foundation
public class LocationByIPRequest: ServiceRequest, Hashable {
// MARK: - Typealiases -
public typealias Data = Result<IPPlace,LocationManager.ErrorReason>
public typealias Callback = ((Data) -> Void)
// MARK: - Public Properties -
/// Unique identifier of the request.
public var id: LocationManager.RequestID
/// Timeout of the request.
public var timeout: Timeout.Mode?
/// Last obtained valid value for request.
public internal(set) var value: IPPlace?
/// Service used
public var service: LocationByIPRequest.Service {
fatalError("Missing service property")
}
/// Timeout manager handles timeout events.
internal var timeoutManager: Timeout? {
didSet {
// Also set the callback to receive timeout event; it will remove the request.
timeoutManager?.callback = { interval in
self.stop(reason: .timeout(interval), remove: true)
}
}
}
/// State of the request.
public var state: RequestState = .idle
/// Registered callbacks.
public var observers = Observers<LocationByIPRequest.Callback>()
// MARK: - Initialization -
init() {
self.id = UUID().uuidString
}
public func stop() {
}
public func start() {
}
public func pause() {
}
internal func stop(reason: LocationManager.ErrorReason = .cancelled, remove: Bool) {
timeoutManager?.reset()
dispatch(data: .failure(reason))
}
internal func dispatch(data: Data, andComplete complete: Bool = false) {
DispatchQueue.main.async {
self.observers.list.forEach {
$0(data)
}
if complete {
LocationManager.shared.removeIPLocationRequest(self)
}
}
}
public static func == (lhs: LocationByIPRequest, rhs: LocationByIPRequest) -> Bool {
return lhs.id == rhs.id
}
public func hash(into hasher: inout Hasher) {
hasher.combine(self.id)
}
}
| mit | 419e0e62a5d1b79692d89730dba4a266 | 25.126316 | 90 | 0.597099 | 4.773077 | false | false | false | false |
hstdt/GodEye | GodEye/Classes/View/Monitor/MonitorBaseView.swift | 2 | 4006 | //
// MonitorPercentView.swift
// Pods
//
// Created by zixun on 17/1/5.
//
//
import Foundation
import SystemEye
enum MonitorBaseViewPosition {
case left
case right
}
class MonitorBaseView: UIButton {
var position:MonitorBaseViewPosition = .left
var firstRow:Bool = true
private(set) var type: MonitorSystemType!
init(type:MonitorSystemType) {
super.init(frame: CGRect.zero)
self.type = type
self.infoLabel.text = type.info
self.contentLabel.text = type.initialValue
self.backgroundColor = UIColor.clear
self.addSubview(self.rightLine)
self.addSubview(self.topLine)
self.addSubview(self.infoLabel)
self.addSubview(self.contentLabel)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
var rect = self.bounds
rect.origin.x = rect.size.width - 0.5
rect.size.width = 0.5
rect.origin.y = 20
rect.size.height -= rect.origin.y * 2
self.rightLine.frame = self.position == .left ? rect : CGRect.zero
rect.origin.x = self.position == .left ? 20 : (self.firstRow ? 0 : 20)
rect.origin.y = 0
rect.size.width = self.frame.size.width - (self.firstRow ? 20 : 40)
rect.size.height = 0.5
self.topLine.frame = rect
rect.size.height = 50
rect.origin.x = 20
rect.size.width = self.frame.size.width - rect.origin.x - 20
rect.origin.y = (self.frame.size.height - rect.size.height) / 2
self.contentLabel.frame = rect
rect.origin.x = 20
rect.origin.y = 10
rect.size.width = self.frame.size.width - 20
rect.size.height = 12
self.infoLabel.frame = rect
}
fileprivate lazy var contentLabel: UILabel = {
let new = UILabel()
new.text = "Unknow"
new.textColor = UIColor.white
new.textAlignment = .right
new.numberOfLines = 0
new.font = UIFont(name: "HelveticaNeue-UltraLight", size: 32)
return new
}()
private(set) lazy var infoLabel: UILabel = {
let new = UILabel()
new.font = UIFont.systemFont(ofSize: 12)
new.textColor = UIColor.white
return new
}()
private lazy var rightLine: UIView = {
let new = UIView()
new.backgroundColor = UIColor.white
return new
}()
private lazy var topLine: UIView = {
let new = UIView()
new.backgroundColor = UIColor.white
return new
}()
}
// MARK: - Tool
extension MonitorBaseView {
fileprivate func attributes(size:CGFloat) -> [String : Any] {
return [NSFontAttributeName:UIFont(name: "HelveticaNeue-UltraLight", size: size),
NSForegroundColorAttributeName:UIColor.white]
}
fileprivate func contentString(_ string:String,unit:String) -> NSAttributedString {
let result = NSMutableAttributedString()
result.append(NSAttributedString(string: string, attributes: self.attributes(size: 32)))
result.append(NSAttributedString(string: unit, attributes: self.attributes(size: 16)))
return result
}
}
// MARK: - Byte
extension MonitorBaseView {
func configure(byte:Double) {
let str = byte.storageCapacity()
self.contentLabel.attributedText = self.contentString(String.init(format: "%.1f", str.capacity), unit: str.unit)
}
}
// MARK: - Percent
extension MonitorBaseView {
func configure(percent:Double) {
self.contentLabel.attributedText = self.contentString(String.init(format: "%.1f", percent), unit: "%")
}
}
extension MonitorBaseView {
func configure(fps: Double) {
self.contentLabel.attributedText = self.contentString(String.init(format: "%.1f", fps), unit: "FPS")
}
}
| mit | fa680a33823d2b143857e8bac269b92b | 27.411348 | 120 | 0.61358 | 4.207983 | false | false | false | false |
beltex/dshb | dshb/WidgetUITitle.swift | 1 | 2056 | //
// WidgetUITitle.swift
// dshb
//
// The MIT License
//
// Copyright (C) 2014-2017 beltex <https://beltex.github.io>
//
// 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 Darwin.ncurses
struct WidgetUITitle {
let name : String
let nameCount: Int
var window : Window
fileprivate var padding = String()
init(name: String, window: Window) {
self.name = name
self.window = window
nameCount = name.characters.count
generatePadding()
}
func draw() {
move(window.point.y, window.point.x)
attrset(COLOR_PAIR(WidgetUIColor.title.rawValue))
addstr(name + padding)
}
mutating func resize(_ window: Window) {
self.window = window
generatePadding()
draw()
}
fileprivate mutating func generatePadding() {
var paddingSize = window.length - nameCount
if paddingSize < 0 { paddingSize = 0 }
padding = String(repeating: " ", count: paddingSize)
}
}
| mit | 656d320713ea5e8ca32e5586fbdd52e3 | 31.125 | 80 | 0.683852 | 4.337553 | false | false | false | false |
Chaosspeeder/YourGoals | YourGoals/UI/Controller/GoalsViewController+CollectionView.swift | 1 | 5726 | //
// GoalsViewController+CollectionView.swift
// YourGoals
//
// Created by André Claaßen on 23.10.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
import UIKit
extension GoalsViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
// MARK: - Configuration
internal func configure(collectionView: UICollectionView) {
self.manager = GoalsStorageManager.defaultStorageManager
collectionView.registerReusableCell(GoalCell2.self)
collectionView.registerReusableCell(NewGoalCell.self)
collectionView.registerSupplementaryView(GoalsSectionHeader.self, kind: UICollectionView.elementKindSectionHeader)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 20, right: 0)
self.reloadGoalsCollection()
}
func reloadGoalsCollection() {
do {
let settings = SettingsUserDefault()
self.strategy = try StrategyManager(manager: self.manager).assertValidActiveStrategy()
self.goals = strategy.allGoalsByPrio(withBackburned: settings.backburnedGoals)
self.collectionView.reloadData()
}
catch let error {
showNotification(forError: error)
}
}
// MARK: - Goal Handling helper methods
func numberOfGoals() -> Int {
return self.goals.count
}
func goalForIndexPath(path:IndexPath) -> Goal {
return self.goals[path.row]
}
// MARK: - UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfGoals() + 1 // one for the new goal entry
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
do {
if indexPath.row == numberOfGoals() {
let newGoalCell = NewGoalCell.dequeue(fromCollectionView: collectionView, atIndexPath: indexPath)
newGoalCell.configure(owner: self)
return newGoalCell
} else {
let date = Date()
let goalCell = GoalCell2.dequeue(fromCollectionView: collectionView, atIndexPath: indexPath)
let goal = self.goalForIndexPath(path: indexPath)
try goalCell.show(goal: goal, forDate: date, goalIsActive: goal.isActive(forDate: date), backburnedGoals: goal.backburnedGoals, manager: self.manager)
return goalCell
}
}
catch let error {
self.showNotification(forError: error)
return UICollectionViewCell()
}
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if UIDevice.current.userInterfaceIdiom == .phone {
return CGSize(width: collectionView.bounds.width, height: BaseRoundedCardCell.cellHeight)
} else {
// Number of Items per Row
let numberOfItemsInRow = 2
// Current Row Number
let rowNumber = indexPath.item/numberOfItemsInRow
// Compressed With
let compressedWidth = collectionView.bounds.width/3
// Expanded Width
let expandedWidth = (collectionView.bounds.width/3) * 2
// Is Even Row
let isEvenRow = rowNumber % 2 == 0
// Is First Item in Row
let isFirstItem = indexPath.item % numberOfItemsInRow != 0
// Calculate Width
var width: CGFloat = 0.0
if isEvenRow {
width = isFirstItem ? compressedWidth : expandedWidth
} else {
width = isFirstItem ? expandedWidth : compressedWidth
}
return CGSize(width: width, height: BaseRoundedCardCell.cellHeight)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: GoalsSectionHeader.viewHeight)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let sectionHeader = GoalsSectionHeader.dequeue(fromCollectionView: collectionView, ofKind: kind, atIndexPath: indexPath)
sectionHeader.shouldShowProfileImageView = (indexPath.section == 0)
return sectionHeader
}
// MARK: - UICollectionViewDelegate
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let animationSourceMetrics = collectionView.cellForItem(at: indexPath) as? TransitionAnimationSourceMetrics {
let metrics = animationSourceMetrics.animationMetrics(relativeTo: self.view)
presentStoryAnimationController.selectedCardMetrics = metrics
dismissStoryAnimationController.selectedCardMetrics = metrics
}
self.selectedGoal = goalForIndexPath(path: indexPath)
performSegue(withIdentifier: "presentShowGoal", sender: self)
}
}
| lgpl-3.0 | c83a25baefb325bd1a6037137ff52e83 | 39.574468 | 170 | 0.652508 | 5.778788 | false | false | false | false |
exyte/Macaw | Source/model/geom2d/Size.swift | 1 | 873 | import Foundation
open class Size {
public let w: Double
public let h: Double
public static let zero = Size(0, 0)
public init(_ w: Double, _ h: Double) {
self.w = w
self.h = h
}
public init(w: Double = 0, h: Double = 0) {
self.w = w
self.h = h
}
open func rect(at point: Point = Point.origin) -> Rect {
return Rect(point: point, size: self)
}
open func angle() -> Double {
return atan2(h, w)
}
}
extension Size {
public static func == (lhs: Size, rhs: Size) -> Bool {
return lhs.w == rhs.w && lhs.h == rhs.h
}
public static func + (lhs: Size, rhs: Size) -> Size {
return Size(w: lhs.w + rhs.w, h: lhs.h + rhs.h)
}
public static func - (lhs: Size, rhs: Size) -> Size {
return Size(w: lhs.w - rhs.w, h: lhs.h - rhs.h)
}
}
| mit | d4978281a6bda63000fbba193a986a51 | 18.840909 | 60 | 0.517755 | 3.174545 | false | false | false | false |
North-American-Signs/DKImagePickerController | Example/DKImagePickerControllerDemo/DKImagePickerControllerDemoVC.swift | 1 | 7704 | //
// DKImagePickerControllerDemoVC.swift
// DKImagePickerControllerDemo
//
// Created by ZhangAo on 03/01/2017.
// Copyright © 2017 ZhangAo. All rights reserved.
//
import UIKit
import DKImagePickerController
import Photos
class DKImagePickerControllerDemoVC: UITableViewController {
fileprivate func imageOnlyAssetFetchOptions() -> PHFetchOptions {
let assetFetchOptions = PHFetchOptions()
assetFetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.image.rawValue)
return assetFetchOptions
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let cell = sender as! UITableViewCell
let destination = segue.destination as! ViewController
destination.title = cell.textLabel?.text
switch segue.identifier! {
case "Pick Any":
let pickerController = DKImagePickerController()
destination.pickerController = pickerController
case "Pick Photos Only":
let pickerController = DKImagePickerController()
pickerController.assetType = .allPhotos
destination.pickerController = pickerController
case "Pick Videos Only":
let pickerController = DKImagePickerController()
pickerController.assetType = .allVideos
destination.pickerController = pickerController
case "Pick Any (Only Photos Or Videos)":
let pickerController = DKImagePickerController()
pickerController.allowMultipleTypes = false
destination.pickerController = pickerController
case "Take A Picture":
let pickerController = DKImagePickerController()
pickerController.sourceType = .camera
destination.pickerController = pickerController
case "Hides Camera":
let pickerController = DKImagePickerController()
pickerController.sourceType = .photo
destination.pickerController = pickerController
case "With GPS":
let pickerController = DKImagePickerController()
pickerController.containsGPSInMetadata = true
destination.pickerController = pickerController
case "Custom Album":
let pickerController = DKImagePickerController()
pickerController.sourceType = .camera
pickerController.cameraAlbumName = "DKImagePickerAlbum"
destination.pickerController = pickerController
case "Allows Landscape":
let pickerController = DKImagePickerController()
pickerController.allowsLandscape = true
destination.pickerController = pickerController
case "Single Select":
let pickerController = DKImagePickerController()
pickerController.singleSelect = true
pickerController.autoCloseOnSingleSelect = true
destination.pickerController = pickerController
case "Swiping to select":
let pickerController = DKImagePickerController()
pickerController.allowSwipeToSelect = true
destination.pickerController = pickerController
case "Select All":
let pickerController = DKImagePickerController()
pickerController.allowSelectAll = true
destination.pickerController = pickerController
case "Custom Camera":
let pickerController = DKImagePickerController()
DKImageExtensionController.registerExtension(extensionClass: CustomCameraExtension.self, for: .camera)
destination.pickerController = pickerController
case "Custom Inline Camera":
let pickerController = DKImagePickerController()
pickerController.sourceType = .camera
pickerController.modalPresentationStyle = .overCurrentContext
DKImageExtensionController.registerExtension(extensionClass: CustomCameraExtension.self, for: .inlineCamera)
destination.pickerController = pickerController
case "Custom UI":
let pickerController = DKImagePickerController()
pickerController.sourceType = .photo
pickerController.UIDelegate = CustomUIDelegate()
pickerController.showsCancelButton = true
destination.pickerController = pickerController
case "Custom Layout":
let pickerController = DKImagePickerController()
pickerController.UIDelegate = CustomLayoutUIDelegate()
destination.pickerController = pickerController
case "Inline":
let groupDataManagerConfiguration = DKImageGroupDataManagerConfiguration()
groupDataManagerConfiguration.fetchLimit = 10
groupDataManagerConfiguration.assetGroupTypes = [.smartAlbumUserLibrary]
// To specify photos only, we'd typically use pickerController.assetType = .allPhotos.
// Because we're specifying a custom DKImageGroupDataManager, that doesn't work,
// and we have to specify it using assetFetchOptions.
groupDataManagerConfiguration.assetFetchOptions = imageOnlyAssetFetchOptions()
let groupDataManager = DKImageGroupDataManager(configuration: groupDataManagerConfiguration)
let pickerController = DKImagePickerController(groupDataManager: groupDataManager)
pickerController.inline = true
pickerController.UIDelegate = CustomInlineLayoutUIDelegate()
pickerController.sourceType = .photo
destination.pickerController = pickerController
case "Export automatically":
let pickerController = DKImagePickerController()
pickerController.exportsWhenCompleted = true
destination.pickerController = pickerController
case "Export manually":
let pickerController = DKImagePickerController()
destination.exportManually = true
destination.pickerController = pickerController
case "Custom localized strings":
DKImagePickerControllerResource.customLocalizationBlock = { title in
if title == "picker.select.title" {
return "Test(%@)"
} else {
return nil
}
}
let pickerController = DKImagePickerController()
destination.pickerController = pickerController
case "Custom localized images":
DKImagePickerControllerResource.customImageBlock = { imageName in
if imageName == "camera" {
return DKImagePickerControllerResource.photoGalleryCheckedImage()
} else {
return nil
}
}
let pickerController = DKImagePickerController()
destination.pickerController = pickerController
case "Reload":
let pickerController = DKImagePickerController()
pickerController.UIDelegate = ReloadUIDelegate()
destination.pickerController = pickerController
default:
assert(false)
}
}
}
| mit | a4b2672a39d4a80c2219889393276334 | 38.30102 | 120 | 0.622874 | 7.657058 | false | false | false | false |
matthewpurcell/firefox-ios | Providers/Profile.swift | 1 | 40055 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Account
import ReadingList
import Shared
import Storage
import Sync
import XCGLogger
import SwiftKeychainWrapper
import Deferred
private let log = Logger.syncLogger
public let NotificationProfileDidStartSyncing = "NotificationProfileDidStartSyncing"
public let NotificationProfileDidFinishSyncing = "NotificationProfileDidFinishSyncing"
public let ProfileRemoteTabsSyncDelay: NSTimeInterval = 0.1
public protocol SyncManager {
var isSyncing: Bool { get }
var lastSyncFinishTime: Timestamp? { get set }
func hasSyncedHistory() -> Deferred<Maybe<Bool>>
func hasSyncedLogins() -> Deferred<Maybe<Bool>>
func syncClients() -> SyncResult
func syncClientsThenTabs() -> SyncResult
func syncHistory() -> SyncResult
func syncLogins() -> SyncResult
func syncEverything() -> Success
// The simplest possible approach.
func beginTimedSyncs()
func endTimedSyncs()
func applicationDidEnterBackground()
func applicationDidBecomeActive()
func onNewProfile()
func onRemovedAccount(account: FirefoxAccount?) -> Success
func onAddedAccount() -> Success
}
typealias EngineIdentifier = String
typealias SyncFunction = (SyncDelegate, Prefs, Ready) -> SyncResult
class ProfileFileAccessor: FileAccessor {
convenience init(profile: Profile) {
self.init(localName: profile.localName())
}
init(localName: String) {
let profileDirName = "profile.\(localName)"
// Bug 1147262: First option is for device, second is for simulator.
var rootPath: NSString
if let sharedContainerIdentifier = AppInfo.sharedContainerIdentifier(), url = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(sharedContainerIdentifier), path = url.path {
rootPath = path as NSString
} else {
log.error("Unable to find the shared container. Defaulting profile location to ~/Documents instead.")
rootPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]) as NSString
}
super.init(rootPath: rootPath.stringByAppendingPathComponent(profileDirName))
}
}
class CommandStoringSyncDelegate: SyncDelegate {
let profile: Profile
init() {
profile = BrowserProfile(localName: "profile", app: nil)
}
func displaySentTabForURL(URL: NSURL, title: String) {
let item = ShareItem(url: URL.absoluteString, title: title, favicon: nil)
self.profile.queue.addToQueue(item)
}
}
/**
* This exists because the Sync code is extension-safe, and thus doesn't get
* direct access to UIApplication.sharedApplication, which it would need to
* display a notification.
* This will also likely be the extension point for wipes, resets, and
* getting access to data sources during a sync.
*/
let TabSendURLKey = "TabSendURL"
let TabSendTitleKey = "TabSendTitle"
let TabSendCategory = "TabSendCategory"
enum SentTabAction: String {
case View = "TabSendViewAction"
case Bookmark = "TabSendBookmarkAction"
case ReadingList = "TabSendReadingListAction"
}
class BrowserProfileSyncDelegate: SyncDelegate {
let app: UIApplication
init(app: UIApplication) {
self.app = app
}
// SyncDelegate
func displaySentTabForURL(URL: NSURL, title: String) {
// check to see what the current notification settings are and only try and send a notification if
// the user has agreed to them
if let currentSettings = app.currentUserNotificationSettings() {
if currentSettings.types.rawValue & UIUserNotificationType.Alert.rawValue != 0 {
if Logger.logPII {
log.info("Displaying notification for URL \(URL.absoluteString)")
}
let notification = UILocalNotification()
notification.fireDate = NSDate()
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.alertBody = String(format: NSLocalizedString("New tab: %@: %@", comment:"New tab [title] [url]"), title, URL.absoluteString)
notification.userInfo = [TabSendURLKey: URL.absoluteString, TabSendTitleKey: title]
notification.alertAction = nil
notification.category = TabSendCategory
app.presentLocalNotificationNow(notification)
}
}
}
}
/**
* A Profile manages access to the user's data.
*/
protocol Profile: class {
var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> { get }
// var favicons: Favicons { get }
var prefs: Prefs { get }
var queue: TabQueue { get }
var searchEngines: SearchEngines { get }
var files: FileAccessor { get }
var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> { get }
var favicons: Favicons { get }
var readingList: ReadingListService? { get }
var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> { get }
func shutdown()
// I got really weird EXC_BAD_ACCESS errors on a non-null reference when I made this a getter.
// Similar to <http://stackoverflow.com/questions/26029317/exc-bad-access-when-indirectly-accessing-inherited-member-in-swift>.
func localName() -> String
// URLs and account configuration.
var accountConfiguration: FirefoxAccountConfiguration { get }
// Do we have an account at all?
func hasAccount() -> Bool
// Do we have an account that (as far as we know) is in a syncable state?
func hasSyncableAccount() -> Bool
func getAccount() -> FirefoxAccount?
func removeAccount()
func setAccount(account: FirefoxAccount)
func getClients() -> Deferred<Maybe<[RemoteClient]>>
func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>>
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>>
func sendItems(items: [ShareItem], toClients clients: [RemoteClient])
var syncManager: SyncManager { get }
}
public class BrowserProfile: Profile {
private let name: String
internal let files: FileAccessor
weak private var app: UIApplication?
/**
* N.B., BrowserProfile is used from our extensions, often via a pattern like
*
* BrowserProfile(…).foo.saveSomething(…)
*
* This can break if BrowserProfile's initializer does async work that
* subsequently — and asynchronously — expects the profile to stick around:
* see Bug 1218833. Be sure to only perform synchronous actions here.
*/
init(localName: String, app: UIApplication?, clear: Bool = false) {
log.debug("Initing profile \(localName) on thread \(NSThread.currentThread()).")
self.name = localName
self.files = ProfileFileAccessor(localName: localName)
self.app = app
if clear {
do {
try NSFileManager.defaultManager().removeItemAtPath(self.files.rootPath as String)
} catch {
log.info("Cannot clear profile: \(error)")
}
}
let notificationCenter = NSNotificationCenter.defaultCenter()
notificationCenter.addObserver(self, selector: Selector("onLocationChange:"), name: NotificationOnLocationChange, object: nil)
notificationCenter.addObserver(self, selector: Selector("onProfileDidFinishSyncing:"), name: NotificationProfileDidFinishSyncing, object: nil)
notificationCenter.addObserver(self, selector: Selector("onPrivateDataClearedHistory:"), name: NotificationPrivateDataClearedHistory, object: nil)
if let baseBundleIdentifier = AppInfo.baseBundleIdentifier() {
KeychainWrapper.serviceName = baseBundleIdentifier
} else {
log.error("Unable to get the base bundle identifier. Keychain data will not be shared.")
}
// If the profile dir doesn't exist yet, this is first run (for this profile).
if !files.exists("") {
log.info("New profile. Removing old account metadata.")
self.removeAccountMetadata()
self.syncManager.onNewProfile()
prefs.clearAll()
}
// Always start by needing invalidation.
// This is the same as self.history.setTopSitesNeedsInvalidation, but without the
// side-effect of instantiating SQLiteHistory (and thus BrowserDB) on the main thread.
prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
}
// Extensions don't have a UIApplication.
convenience init(localName: String) {
self.init(localName: localName, app: nil)
}
func shutdown() {
log.debug("Shutting down profile.")
if self.dbCreated {
db.forceClose()
}
if self.loginsDBCreated {
loginsDB.forceClose()
}
}
@objc
func onLocationChange(notification: NSNotification) {
if let v = notification.userInfo!["visitType"] as? Int,
let visitType = VisitType(rawValue: v),
let url = notification.userInfo!["url"] as? NSURL where !isIgnoredURL(url),
let title = notification.userInfo!["title"] as? NSString {
// Only record local vists if the change notification originated from a non-private tab
if !(notification.userInfo!["isPrivate"] as? Bool ?? false) {
// We don't record a visit if no type was specified -- that means "ignore me".
let site = Site(url: url.absoluteString, title: title as String)
let visit = SiteVisit(site: site, date: NSDate.nowMicroseconds(), type: visitType)
history.addLocalVisit(visit)
}
history.setTopSitesNeedsInvalidation()
} else {
log.debug("Ignoring navigation.")
}
}
// These selectors run on which ever thread sent the notifications (not the main thread)
@objc
func onProfileDidFinishSyncing(notification: NSNotification) {
history.setTopSitesNeedsInvalidation()
}
@objc
func onPrivateDataClearedHistory(notification: NSNotification) {
// Immediately invalidate the top sites cache
history.refreshTopSitesCache()
}
deinit {
log.debug("Deiniting profile \(self.localName).")
self.syncManager.endTimedSyncs()
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationOnLocationChange, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationPrivateDataClearedHistory, object: nil)
}
func localName() -> String {
return name
}
lazy var queue: TabQueue = {
withExtendedLifetime(self.history) {
return SQLiteQueue(db: self.db)
}
}()
private var dbCreated = false
var db: BrowserDB {
struct Singleton {
static var token: dispatch_once_t = 0
static var instance: BrowserDB!
}
dispatch_once(&Singleton.token) {
Singleton.instance = BrowserDB(filename: "browser.db", files: self.files)
self.dbCreated = true
}
return Singleton.instance
}
/**
* Favicons, history, and bookmarks are all stored in one intermeshed
* collection of tables.
*
* Any other class that needs to access any one of these should ensure
* that this is initialized first.
*/
private lazy var places: protocol<BrowserHistory, Favicons, SyncableHistory, ResettableSyncStorage> = {
return SQLiteHistory(db: self.db, prefs: self.prefs)!
}()
var favicons: Favicons {
return self.places
}
var history: protocol<BrowserHistory, SyncableHistory, ResettableSyncStorage> {
return self.places
}
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination, ResettableSyncStorage, AccountRemovalDelegate> = {
// Make sure the rest of our tables are initialized before we try to read them!
// This expression is for side-effects only.
withExtendedLifetime(self.places) {
return MergedSQLiteBookmarks(db: self.db)
}
}()
lazy var mirrorBookmarks: BookmarkMirrorStorage = {
// Yeah, this is lazy. Sorry.
return self.bookmarks as! MergedSQLiteBookmarks
}()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
}()
func makePrefs() -> Prefs {
return NSUserDefaultsPrefs(prefix: self.localName())
}
lazy var prefs: Prefs = {
return self.makePrefs()
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath as String)
}()
lazy var remoteClientsAndTabs: protocol<RemoteClientsAndTabs, ResettableSyncStorage, AccountRemovalDelegate> = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var syncManager: SyncManager = {
return BrowserSyncManager(profile: self)
}()
private func getSyncDelegate() -> SyncDelegate {
if let app = self.app {
return BrowserProfileSyncDelegate(app: app)
}
return CommandStoringSyncDelegate()
}
public func getClients() -> Deferred<Maybe<[RemoteClient]>> {
return self.syncManager.syncClients()
>>> { self.remoteClientsAndTabs.getClients() }
}
public func getClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.syncManager.syncClientsThenTabs()
>>> { self.remoteClientsAndTabs.getClientsAndTabs() }
}
public func getCachedClientsAndTabs() -> Deferred<Maybe<[ClientAndTabs]>> {
return self.remoteClientsAndTabs.getClientsAndTabs()
}
func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs)
}
public func sendItems(items: [ShareItem], toClients clients: [RemoteClient]) {
let commands = items.map { item in
SyncCommand.fromShareItem(item, withAction: "displayURI")
}
self.remoteClientsAndTabs.insertCommands(commands, forClients: clients) >>> { self.syncManager.syncClients() }
}
lazy var logins: protocol<BrowserLogins, SyncableLogins, ResettableSyncStorage> = {
return SQLiteLogins(db: self.loginsDB)
}()
// This is currently only used within the dispatch_once block in loginsDB, so we don't
// have to worry about races giving us two keys. But if this were ever to be used
// elsewhere, it'd be unsafe, so we wrap this in a dispatch_once, too.
private var loginsKey: String? {
let key = "sqlcipher.key.logins.db"
struct Singleton {
static var token: dispatch_once_t = 0
static var instance: String!
}
dispatch_once(&Singleton.token) {
if KeychainWrapper.hasValueForKey(key) {
let value = KeychainWrapper.stringForKey(key)
Singleton.instance = value
} else {
let Length: UInt = 256
let secret = Bytes.generateRandomBytes(Length).base64EncodedString
KeychainWrapper.setString(secret, forKey: key)
Singleton.instance = secret
}
}
return Singleton.instance
}
private var loginsDBCreated = false
private lazy var loginsDB: BrowserDB = {
struct Singleton {
static var token: dispatch_once_t = 0
static var instance: BrowserDB!
}
dispatch_once(&Singleton.token) {
Singleton.instance = BrowserDB(filename: "logins.db", secretKey: self.loginsKey, files: self.files)
self.loginsDBCreated = true
}
return Singleton.instance
}()
var accountConfiguration: FirefoxAccountConfiguration {
let locale = NSLocale.currentLocale()
if self.prefs.boolForKey("useChinaSyncService") ?? (locale.localeIdentifier == "zh_CN") {
return ChinaEditionFirefoxAccountConfiguration()
}
return ProductionFirefoxAccountConfiguration()
}
private lazy var account: FirefoxAccount? = {
if let dictionary = KeychainWrapper.objectForKey(self.name + ".account") as? [String: AnyObject] {
return FirefoxAccount.fromDictionary(dictionary)
}
return nil
}()
func hasAccount() -> Bool {
return account != nil
}
func hasSyncableAccount() -> Bool {
return account?.actionNeeded == FxAActionNeeded.None
}
func getAccount() -> FirefoxAccount? {
return account
}
func removeAccountMetadata() {
self.prefs.removeObjectForKey(PrefsKeys.KeyLastRemoteTabSyncTime)
KeychainWrapper.removeObjectForKey(self.name + ".account")
}
func removeAccount() {
let old = self.account
removeAccountMetadata()
self.account = nil
// Tell any observers that our account has changed.
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
// Trigger cleanup. Pass in the account in case we want to try to remove
// client-specific data from the server.
self.syncManager.onRemovedAccount(old)
// Deregister for remote notifications.
app?.unregisterForRemoteNotifications()
}
func setAccount(account: FirefoxAccount) {
KeychainWrapper.setObject(account.asDictionary(), forKey: name + ".account")
self.account = account
// register for notifications for the account
registerForNotifications()
// tell any observers that our account has changed
NSNotificationCenter.defaultCenter().postNotificationName(NotificationFirefoxAccountChanged, object: nil)
self.syncManager.onAddedAccount()
}
func registerForNotifications() {
let viewAction = UIMutableUserNotificationAction()
viewAction.identifier = SentTabAction.View.rawValue
viewAction.title = NSLocalizedString("View", comment: "View a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
viewAction.activationMode = UIUserNotificationActivationMode.Foreground
viewAction.destructive = false
viewAction.authenticationRequired = false
let bookmarkAction = UIMutableUserNotificationAction()
bookmarkAction.identifier = SentTabAction.Bookmark.rawValue
bookmarkAction.title = NSLocalizedString("Bookmark", comment: "Bookmark a URL - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
bookmarkAction.activationMode = UIUserNotificationActivationMode.Foreground
bookmarkAction.destructive = false
bookmarkAction.authenticationRequired = false
let readingListAction = UIMutableUserNotificationAction()
readingListAction.identifier = SentTabAction.ReadingList.rawValue
readingListAction.title = NSLocalizedString("Add to Reading List", comment: "Add URL to the reading list - https://bugzilla.mozilla.org/attachment.cgi?id=8624438, https://bug1157303.bugzilla.mozilla.org/attachment.cgi?id=8624440")
readingListAction.activationMode = UIUserNotificationActivationMode.Foreground
readingListAction.destructive = false
readingListAction.authenticationRequired = false
let sentTabsCategory = UIMutableUserNotificationCategory()
sentTabsCategory.identifier = TabSendCategory
sentTabsCategory.setActions([readingListAction, bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Default)
sentTabsCategory.setActions([bookmarkAction, viewAction], forContext: UIUserNotificationActionContext.Minimal)
app?.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Alert, categories: [sentTabsCategory]))
app?.registerForRemoteNotifications()
}
// Extends NSObject so we can use timers.
class BrowserSyncManager: NSObject, SyncManager {
// We shouldn't live beyond our containing BrowserProfile, either in the main app or in
// an extension.
// But it's possible that we'll finish a side-effect sync after we've ditched the profile
// as a whole, so we hold on to our Prefs, potentially for a little while longer. This is
// safe as a strong reference, because there's no cycle.
unowned private let profile: BrowserProfile
private let prefs: Prefs
let FifteenMinutes = NSTimeInterval(60 * 15)
let OneMinute = NSTimeInterval(60)
private var syncTimer: NSTimer? = nil
private var backgrounded: Bool = true
func applicationDidEnterBackground() {
self.backgrounded = true
self.endTimedSyncs()
}
func applicationDidBecomeActive() {
self.backgrounded = false
guard self.profile.hasAccount() else {
return
}
self.beginTimedSyncs()
// Sync now if it's been more than our threshold.
let now = NSDate.now()
let then = self.lastSyncFinishTime ?? 0
let since = now - then
log.debug("\(since)msec since last sync.")
if since > SyncConstants.SyncOnForegroundMinimumDelayMillis {
self.syncEverythingSoon()
}
}
/**
* Locking is managed by withSyncInputs. Make sure you take and release these
* whenever you do anything Sync-ey.
*/
var syncLock = OSSpinLock() {
didSet {
let notification = syncLock == 0 ? NotificationProfileDidFinishSyncing : NotificationProfileDidStartSyncing
NSNotificationCenter.defaultCenter().postNotification(NSNotification(name: notification, object: nil))
}
}
// According to the OSAtomic header documentation, the convention for an unlocked lock is a zero value
// and a locked lock is a non-zero value
var isSyncing: Bool {
return syncLock != 0
}
private func beginSyncing() -> Bool {
return OSSpinLockTry(&syncLock)
}
private func endSyncing() {
OSSpinLockUnlock(&syncLock)
}
init(profile: BrowserProfile) {
self.profile = profile
self.prefs = profile.prefs
super.init()
let center = NSNotificationCenter.defaultCenter()
center.addObserver(self, selector: "onDatabaseWasRecreated:", name: NotificationDatabaseWasRecreated, object: nil)
center.addObserver(self, selector: "onLoginDidChange:", name: NotificationDataLoginDidChange, object: nil)
center.addObserver(self, selector: "onFinishSyncing:", name: NotificationProfileDidFinishSyncing, object: nil)
}
deinit {
// Remove 'em all.
let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self, name: NotificationDatabaseWasRecreated, object: nil)
center.removeObserver(self, name: NotificationDataLoginDidChange, object: nil)
center.removeObserver(self, name: NotificationProfileDidFinishSyncing, object: nil)
}
private func handleRecreationOfDatabaseNamed(name: String?) -> Success {
let loginsCollections = ["passwords"]
let browserCollections = ["bookmarks", "history", "tabs"]
switch name ?? "<all>" {
case "<all>":
return self.locallyResetCollections(loginsCollections + browserCollections)
case "logins.db":
return self.locallyResetCollections(loginsCollections)
case "browser.db":
return self.locallyResetCollections(browserCollections)
default:
log.debug("Unknown database \(name).")
return succeed()
}
}
func doInBackgroundAfter(millis millis: Int64, _ block: dispatch_block_t) {
let delay = millis * Int64(NSEC_PER_MSEC)
let when = dispatch_time(DISPATCH_TIME_NOW, delay)
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)
dispatch_after(when, queue, block)
}
@objc
func onDatabaseWasRecreated(notification: NSNotification) {
log.debug("Database was recreated.")
let name = notification.object as? String
log.debug("Database was \(name).")
// We run this in the background after a few hundred milliseconds;
// it doesn't really matter when it runs, so long as it doesn't
// happen in the middle of a sync. We take the lock to prevent that.
self.doInBackgroundAfter(millis: 300) {
OSSpinLockLock(&self.syncLock)
self.handleRecreationOfDatabaseNamed(name).upon { res in
log.debug("Reset of \(name) done: \(res.isSuccess)")
OSSpinLockUnlock(&self.syncLock)
}
}
}
// Simple in-memory rate limiting.
var lastTriggeredLoginSync: Timestamp = 0
@objc func onLoginDidChange(notification: NSNotification) {
log.debug("Login did change.")
if (NSDate.now() - lastTriggeredLoginSync) > OneMinuteInMilliseconds {
lastTriggeredLoginSync = NSDate.now()
// Give it a few seconds.
let when: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, SyncConstants.SyncDelayTriggered)
// Trigger on the main queue. The bulk of the sync work runs in the background.
let greenLight = self.greenLight()
dispatch_after(when, dispatch_get_main_queue()) {
if greenLight() {
self.syncLogins()
}
}
}
}
var lastSyncFinishTime: Timestamp? {
get {
return self.prefs.timestampForKey(PrefsKeys.KeyLastSyncFinishTime)
}
set(value) {
if let value = value {
self.prefs.setTimestamp(value, forKey: PrefsKeys.KeyLastSyncFinishTime)
} else {
self.prefs.removeObjectForKey(PrefsKeys.KeyLastSyncFinishTime)
}
}
}
@objc func onFinishSyncing(notification: NSNotification) {
self.lastSyncFinishTime = NSDate.now()
}
var prefsForSync: Prefs {
return self.prefs.branch("sync")
}
func onAddedAccount() -> Success {
self.beginTimedSyncs();
return self.syncEverything()
}
func locallyResetCollections(collections: [String]) -> Success {
return walk(collections, f: self.locallyResetCollection)
}
func locallyResetCollection(collection: String) -> Success {
switch collection {
case "bookmarks":
return MirroringBookmarksSynchronizer.resetSynchronizerWithStorage(self.profile.bookmarks, basePrefs: self.prefsForSync, collection: "bookmarks")
case "clients":
fallthrough
case "tabs":
// Because clients and tabs share storage, and thus we wipe data for both if we reset either,
// we reset the prefs for both at the same time.
return TabsSynchronizer.resetClientsAndTabsWithStorage(self.profile.remoteClientsAndTabs, basePrefs: self.prefsForSync)
case "history":
return HistorySynchronizer.resetSynchronizerWithStorage(self.profile.history, basePrefs: self.prefsForSync, collection: "history")
case "passwords":
return LoginsSynchronizer.resetSynchronizerWithStorage(self.profile.logins, basePrefs: self.prefsForSync, collection: "passwords")
case "forms":
log.debug("Requested reset for forms, but this client doesn't sync them yet.")
return succeed()
case "addons":
log.debug("Requested reset for addons, but this client doesn't sync them.")
return succeed()
case "prefs":
log.debug("Requested reset for prefs, but this client doesn't sync them.")
return succeed()
default:
log.warning("Asked to reset collection \(collection), which we don't know about.")
return succeed()
}
}
func onNewProfile() {
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
func onRemovedAccount(account: FirefoxAccount?) -> Success {
let profile = self.profile
// Run these in order, because they might write to the same DB!
let remove = [
profile.history.onRemovedAccount,
profile.remoteClientsAndTabs.onRemovedAccount,
profile.logins.onRemovedAccount,
profile.bookmarks.onRemovedAccount,
]
let clearPrefs: () -> Success = {
withExtendedLifetime(self) {
// Clear prefs after we're done clearing everything else -- just in case
// one of them needs the prefs and we race. Clear regardless of success
// or failure.
// This will remove keys from the Keychain if they exist, as well
// as wiping the Sync prefs.
SyncStateMachine.clearStateFromPrefs(self.prefsForSync)
}
return succeed()
}
return accumulate(remove) >>> clearPrefs
}
private func repeatingTimerAtInterval(interval: NSTimeInterval, selector: Selector) -> NSTimer {
return NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: selector, userInfo: nil, repeats: true)
}
func beginTimedSyncs() {
if self.syncTimer != nil {
log.debug("Already running sync timer.")
return
}
let interval = FifteenMinutes
let selector = Selector("syncOnTimer")
log.debug("Starting sync timer.")
self.syncTimer = repeatingTimerAtInterval(interval, selector: selector)
}
/**
* The caller is responsible for calling this on the same thread on which it called
* beginTimedSyncs.
*/
func endTimedSyncs() {
if let t = self.syncTimer {
log.debug("Stopping sync timer.")
self.syncTimer = nil
t.invalidate()
}
}
private func syncClientsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing clients to storage.")
let clientSynchronizer = ready.synchronizer(ClientsSynchronizer.self, delegate: delegate, prefs: prefs)
return clientSynchronizer.synchronizeLocalClients(self.profile.remoteClientsAndTabs, withServer: ready.client, info: ready.info)
}
private func syncTabsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
let storage = self.profile.remoteClientsAndTabs
let tabSynchronizer = ready.synchronizer(TabsSynchronizer.self, delegate: delegate, prefs: prefs)
return tabSynchronizer.synchronizeLocalTabs(storage, withServer: ready.client, info: ready.info)
}
private func syncHistoryWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing history to storage.")
let historySynchronizer = ready.synchronizer(HistorySynchronizer.self, delegate: delegate, prefs: prefs)
return historySynchronizer.synchronizeLocalHistory(self.profile.history, withServer: ready.client, info: ready.info, greenLight: self.greenLight())
}
private func syncLoginsWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Syncing logins to storage.")
let loginsSynchronizer = ready.synchronizer(LoginsSynchronizer.self, delegate: delegate, prefs: prefs)
return loginsSynchronizer.synchronizeLocalLogins(self.profile.logins, withServer: ready.client, info: ready.info)
}
private func mirrorBookmarksWithDelegate(delegate: SyncDelegate, prefs: Prefs, ready: Ready) -> SyncResult {
log.debug("Mirroring server bookmarks to storage.")
let bookmarksMirrorer = ready.synchronizer(MirroringBookmarksSynchronizer.self, delegate: delegate, prefs: prefs)
return bookmarksMirrorer.mirrorBookmarksToStorage(self.profile.mirrorBookmarks, withServer: ready.client, info: ready.info, greenLight: self.greenLight())
}
func takeActionsOnEngineStateChanges<T: EngineStateChanges>(changes: T) -> Deferred<Maybe<T>> {
var needReset = Set<String>(changes.collectionsThatNeedLocalReset())
needReset.unionInPlace(changes.enginesDisabled())
needReset.unionInPlace(changes.enginesEnabled())
if needReset.isEmpty {
log.debug("No collections need reset. Moving on.")
return deferMaybe(changes)
}
// needReset needs at most one of clients and tabs, because we reset them
// both if either needs reset. This is strictly an optimization to avoid
// doing duplicate work.
if needReset.contains("clients") {
if needReset.remove("tabs") != nil {
log.debug("Already resetting clients (and tabs); not bothering to also reset tabs again.")
}
}
return walk(Array(needReset), f: self.locallyResetCollection)
>>> effect(changes.clearLocalCommands)
>>> always(changes)
}
/**
* Returns nil if there's no account.
*/
private func withSyncInputs<T>(label: EngineIdentifier? = nil, function: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<T>>) -> Deferred<Maybe<T>>? {
if let account = profile.account {
if !beginSyncing() {
log.info("Not syncing \(label); already syncing something.")
return deferMaybe(AlreadySyncingError())
}
if let label = label {
log.info("Syncing \(label).")
}
let authState = account.syncAuthState
let readyDeferred = SyncStateMachine(prefs: self.prefsForSync).toReady(authState)
let delegate = profile.getSyncDelegate()
let go = readyDeferred >>== self.takeActionsOnEngineStateChanges >>== { ready in
function(delegate, self.prefsForSync, ready)
}
// Always unlock when we're done.
go.upon({ res in self.endSyncing() })
return go
}
log.warning("No account; can't sync.")
return nil
}
/**
* Runs the single provided synchronization function and returns its status.
*/
private func sync(label: EngineIdentifier, function: (SyncDelegate, Prefs, Ready) -> SyncResult) -> SyncResult {
return self.withSyncInputs(label, function: function) ??
deferMaybe(.NotStarted(.NoAccount))
}
/**
* Runs each of the provided synchronization functions with the same inputs.
* Returns an array of IDs and SyncStatuses the same length as the input.
*/
private func syncSeveral(synchronizers: (EngineIdentifier, SyncFunction)...) -> Deferred<Maybe<[(EngineIdentifier, SyncStatus)]>> {
typealias Pair = (EngineIdentifier, SyncStatus)
let combined: (SyncDelegate, Prefs, Ready) -> Deferred<Maybe<[Pair]>> = { delegate, syncPrefs, ready in
let thunks = synchronizers.map { (i, f) in
return { () -> Deferred<Maybe<Pair>> in
log.debug("Syncing \(i)…")
return f(delegate, syncPrefs, ready) >>== { deferMaybe((i, $0)) }
}
}
return accumulate(thunks)
}
return self.withSyncInputs(nil, function: combined) ??
deferMaybe(synchronizers.map { ($0.0, .NotStarted(.NoAccount)) })
}
func syncEverything() -> Success {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate),
("logins", self.syncLoginsWithDelegate),
("bookmarks", self.mirrorBookmarksWithDelegate),
("history", self.syncHistoryWithDelegate)
) >>> succeed
}
func syncEverythingSoon() {
self.doInBackgroundAfter(millis: SyncConstants.SyncOnForegroundAfterMillis) {
log.debug("Running delayed startup sync.")
self.syncEverything()
}
}
@objc func syncOnTimer() {
self.syncEverything()
}
func hasSyncedHistory() -> Deferred<Maybe<Bool>> {
return self.profile.history.hasSyncedHistory()
}
func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
return self.profile.logins.hasSyncedLogins()
}
func syncClients() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("clients", function: syncClientsWithDelegate)
}
func syncClientsThenTabs() -> SyncResult {
return self.syncSeveral(
("clients", self.syncClientsWithDelegate),
("tabs", self.syncTabsWithDelegate)
) >>== { statuses in
let tabsStatus = statuses[1].1
return deferMaybe(tabsStatus)
}
}
func syncLogins() -> SyncResult {
return self.sync("logins", function: syncLoginsWithDelegate)
}
func syncHistory() -> SyncResult {
// TODO: recognize .NotStarted.
return self.sync("history", function: syncHistoryWithDelegate)
}
func mirrorBookmarks() -> SyncResult {
return self.sync("bookmarks", function: mirrorBookmarksWithDelegate)
}
/**
* Return a thunk that continues to return true so long as an ongoing sync
* should continue.
*/
func greenLight() -> () -> Bool {
let start = NSDate.now()
// Give it one minute to run before we stop.
let stopBy = start + OneMinuteInMilliseconds
log.debug("Checking green light. Backgrounded: \(self.backgrounded).")
return {
!self.backgrounded &&
NSDate.now() < stopBy &&
self.profile.hasSyncableAccount()
}
}
}
}
class AlreadySyncingError: MaybeErrorType {
var description: String {
return "Already syncing."
}
}
| mpl-2.0 | 118920836225349c9aa772db36da547d | 39.246231 | 238 | 0.636684 | 5.386012 | false | false | false | false |
matthewpurcell/firefox-ios | Utils/Extensions/UIViewExtensions.swift | 7 | 1920 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
extension UIView {
/**
* Takes a screenshot of the view with the given size.
*/
func screenshot(size: CGSize, offset: CGPoint? = nil, quality: CGFloat = 1) -> UIImage? {
assert(0...1 ~= quality)
let offset = offset ?? CGPointMake(0, 0)
UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.mainScreen().scale * quality)
drawViewHierarchyInRect(CGRect(origin: offset, size: frame.size), afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
/**
* Takes a screenshot of the view with the given aspect ratio.
* An aspect ratio of 0 means capture the entire view.
*/
func screenshot(aspectRatio: CGFloat = 0, offset: CGPoint? = nil, quality: CGFloat = 1) -> UIImage? {
assert(aspectRatio >= 0)
var size: CGSize
if aspectRatio > 0 {
size = CGSize()
let viewAspectRatio = frame.width / frame.height
if viewAspectRatio > aspectRatio {
size.height = frame.height
size.width = size.height * aspectRatio
} else {
size.width = frame.width
size.height = size.width / aspectRatio
}
} else {
size = frame.size
}
return screenshot(size, offset: offset, quality: quality)
}
/*
* Performs a deep copy of the view. Does not copy constraints.
*/
func clone() -> UIView {
let data = NSKeyedArchiver.archivedDataWithRootObject(self)
return NSKeyedUnarchiver.unarchiveObjectWithData(data) as! UIView
}
} | mpl-2.0 | 3d905342dd45d019f5574d26271fd498 | 33.303571 | 105 | 0.616146 | 4.81203 | false | false | false | false |
wcochran/solitaire-iOS | Solitaire/CardLayer.swift | 1 | 2405 | //
// CardLayer.swift
// Solitaire
//
// Created by Wayne Cochran on 4/4/16.
// Copyright © 2016 Wayne Cochran. All rights reserved.
//
import UIKit
func imageForCard(_ card : Card) -> UIImage {
let suits = [
"spades", "clubs", "diamonds", "hearts"
]
let ranks = [
"", "a", "2", "3", "4", "5", "6", "7", "8", "9", "10", "j", "q", "k"
]
let imageName = "150/\(suits[Int(card.suit.rawValue)])-\(ranks[Int(card.rank)])-150.png"
let image = UIImage(named: imageName, in: nil, compatibleWith: nil)!
return image
}
class CardLayer: CALayer {
let card : Card
var faceUp : Bool {
didSet {
if faceUp != oldValue {
let image = faceUp ? frontImage : CardLayer.backImage
self.contents = image?.cgImage
}
}
}
let frontImage : UIImage
static let backImage = UIImage(named: "150/back-blue-150-1.png", in: nil, compatibleWith: nil)
init(card : Card) {
self.card = card
faceUp = true
frontImage = imageForCard(card)
super.init()
self.contents = frontImage.cgImage
self.contentsGravity = kCAGravityResizeAspect
}
//
// This initializer is used to create shadow copies of layers,
// for example, for the presentationLayer method.
// See the docs:
// https://developer.apple.com/library/mac/documentation/GraphicsImaging/Reference/CALayer_class/#//apple_ref/occ/instm/CALayer/initWithLayer:
//
override init(layer: Any) {
if let layer = layer as? CardLayer {
card = layer.card
faceUp = layer.faceUp
frontImage = layer.frontImage
} else {
card = Card(suit: Suit.spades, rank: ACE)
faceUp = true
frontImage = imageForCard(card)
}
super.init(layer: layer)
self.contents = frontImage.cgImage
self.contentsGravity = kCAGravityResizeAspect
}
//
// This is only needed when a CardLayer is deserialized
// out of a NIB, which should never happen in this app.
// http://www.edwardhuynh.com/blog/2015/02/16/swift-initializer-confusion/
//
required init?(coder aDecoder: NSCoder) {
card = Card(suit: Suit.spades, rank: ACE)
faceUp = true
frontImage = imageForCard(card)
super.init(coder: aDecoder)
}
}
| mit | 2cbc4d7af82ff53f5304dd814a00bd9d | 29.820513 | 147 | 0.586106 | 3.785827 | false | false | false | false |
minikin/Algorithmics | Pods/PSOperations/PSOperations/URLSessionTaskOperation.swift | 1 | 2258 | /*
Copyright (C) 2015 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Shows how to lift operation-like objects in to the NSOperation world.
*/
import Foundation
private var URLSessionTaskOperationKVOContext = 0
/**
`URLSessionTaskOperation` is an `Operation` that lifts an `NSURLSessionTask`
into an operation.
Note that this operation does not participate in any of the delegate callbacks \
of an `NSURLSession`, but instead uses Key-Value-Observing to know when the
task has been completed. It also does not get notified about any errors that
occurred during execution of the task.
An example usage of `URLSessionTaskOperation` can be seen in the `DownloadEarthquakesOperation`.
*/
public class URLSessionTaskOperation: Operation {
let task: NSURLSessionTask
private var observerRemoved = false
private let stateLock = NSLock()
public init(task: NSURLSessionTask) {
assert(task.state == .Suspended, "Tasks must be suspended.")
self.task = task
super.init()
addObserver(BlockObserver(cancelHandler: { _ in
task.cancel()
}))
}
override public func execute() {
assert(task.state == .Suspended, "Task was resumed by something other than \(self).")
task.addObserver(self, forKeyPath: "state", options: NSKeyValueObservingOptions(), context: &URLSessionTaskOperationKVOContext)
task.resume()
}
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard context == &URLSessionTaskOperationKVOContext else { return }
stateLock.withCriticalScope {
if object === task && keyPath == "state" && !observerRemoved {
switch task.state {
case .Completed:
finish()
fallthrough
case .Canceling:
observerRemoved = true
task.removeObserver(self, forKeyPath: "state")
default:
return
}
}
}
}
}
| mit | 58b5869f5283fa7778208db8ba6d0000 | 33.181818 | 164 | 0.635638 | 5.410072 | false | false | false | false |
cbrentharris/swift | stdlib/public/SDK/Foundation/NSStringAPI.swift | 1 | 58889 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 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
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
@warn_unused_result
func _toNSArray<T, U : AnyObject>(a: [T], @noescape f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.addObject(f(s))
}
return result
}
@warn_unused_result
func _toNSRange(r: Range<String.Index>) -> NSRange {
return NSRange(
location: r.startIndex._utf16Index,
length: r.endIndex._utf16Index - r.startIndex._utf16Index)
}
@warn_unused_result
func _countFormatSpecifiers(a: String) -> Int {
// The implementation takes advantage of the fact that internal
// representation of String is UTF-16. Because we only care about the ASCII
// percent character, we don't need to decode UTF-16.
let percentUTF16 = UTF16.CodeUnit(("%" as UnicodeScalar).value)
let notPercentUTF16: UTF16.CodeUnit = 0
var lastChar = notPercentUTF16 // anything other than % would work here
var count = 0
for c in a.utf16 {
if lastChar == percentUTF16 {
if c == percentUTF16 {
// a "%" following this one should not be taken as literal
lastChar = notPercentUTF16
}
else {
++count
lastChar = c
}
} else {
lastChar = c
}
}
return count
}
extension String {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
var _ns: NSString {
return self as NSString
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
@warn_unused_result
func _index(utf16Index: Int) -> Index {
return Index(_base: String.UnicodeScalarView.Index(utf16Index, _core))
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
@warn_unused_result
func _range(r: NSRange) -> Range<Index> {
return _index(r.location)..<_index(r.location + r.length)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
@warn_unused_result
func _optionalRange(r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return .None
}
return _range(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
index: UnsafeMutablePointer<Index>,
@noescape body: (UnsafeMutablePointer<Int>)->Result
) -> Result {
var utf16Index: Int = 0
let result = index._withBridgeValue(&utf16Index) {
body($0)
}
index._setIfNonNil { self._index(utf16Index) }
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
range: UnsafeMutablePointer<Range<Index>>,
@noescape body: (UnsafeMutablePointer<NSRange>)->Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = range._withBridgeValue(&nsRange) {
body($0)
}
range._setIfNonNil { self._range(nsRange) }
return result
}
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// + (const NSStringEncoding *)availableStringEncodings
/// Returns an Array of the encodings string objects support
/// in the application’s environment.
@warn_unused_result
public static func availableStringEncodings() -> [NSStringEncoding] {
var result = [NSStringEncoding]()
var p = NSString.availableStringEncodings()
while p.memory != 0 {
result.append(p.memory)
++p
}
return result
}
// + (NSStringEncoding)defaultCStringEncoding
/// Returns the C-string encoding assumed for any method accepting
/// a C string as an argument.
@warn_unused_result
public static func defaultCStringEncoding() -> NSStringEncoding {
return NSString.defaultCStringEncoding()
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of a given encoding.
@warn_unused_result
public static func localizedNameOfStringEncoding(
encoding: NSStringEncoding
) -> String {
return NSString.localizedNameOfStringEncoding(encoding)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
@warn_unused_result
public static func localizedStringWithFormat(
format: String, _ arguments: CVarArgType...
) -> String {
return String(format: format, locale: NSLocale.currentLocale(),
arguments: arguments)
}
// + (NSString *)pathWithComponents:(NSArray *)components
/// Returns a string built from the strings in a given array
/// by concatenating them with a path separator between each pair.
@available(*, unavailable, message="Use fileURLWithPathComponents on NSURL instead.")
public static func pathWithComponents(components: [String]) -> String {
return NSString.pathWithComponents(components)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Produces a string created by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(UTF8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(UTF8String: bytes) {
self = ns as String
} else {
return nil
}
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the
/// `String` can be converted to a given encoding without loss of
/// information.
@warn_unused_result
public func canBeConvertedToEncoding(encoding: NSStringEncoding) -> Bool {
return _ns.canBeConvertedToEncoding(encoding)
}
// @property NSString* capitalizedString
/// Produce a string with the first character from each word changed
/// to the corresponding uppercase value.
public var capitalizedString: String {
return _ns.capitalizedString as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the `String` that is produced
/// using the current locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedCapitalizedString: String {
return _ns.localizedCapitalizedString
}
// - (NSString *)capitalizedStringWithLocale:(NSLocale *)locale
/// Returns a capitalized representation of the `String`
/// using the specified locale.
@warn_unused_result
public func capitalizedStringWithLocale(locale: NSLocale?) -> String {
return _ns.capitalizedStringWithLocale(locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
@warn_unused_result
public func caseInsensitiveCompare(aString: String) -> NSComparisonResult {
return _ns.caseInsensitiveCompare(aString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(NSStringCompareOptions)mask
/// Returns a string containing characters the `String` and a
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren’t equivalent.
@warn_unused_result
public func commonPrefixWithString(
aString: String, options: NSStringCompareOptions) -> String {
return _ns.commonPrefixWithString(aString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(NSStringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(NSStringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(NSStringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
@warn_unused_result
public func compare(
aString: String,
options mask: NSStringCompareOptions = [],
range: Range<Index>? = nil,
locale: NSLocale? = nil
) -> NSComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
return locale != nil ? _ns.compare(
aString, options: mask,
range: _toNSRange(range ?? self.characters.indices),
locale: locale)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toNSRange(range ?? self.characters.indices))
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the `String` as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the `String`.
/// Returns the actual number of matching paths.
@warn_unused_result
public func completePathIntoString(
outputName: UnsafeMutablePointer<String> = nil,
caseSensitive: Bool,
matchesIntoArray: UnsafeMutablePointer<[String]> = nil,
filterTypes: [String]? = nil
) -> Int {
var nsMatches: NSArray?
var nsOutputName: NSString?
let result = outputName._withBridgeObject(&nsOutputName) {
outputName in matchesIntoArray._withBridgeObject(&nsMatches) {
matchesIntoArray in
self._ns.completePathIntoString(
outputName, caseSensitive: caseSensitive,
matchesIntoArray: matchesIntoArray, filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
matchesIntoArray._setIfNonNil { _convertNSArrayToArray(matches) }
}
if let n = nsOutputName {
outputName._setIfNonNil { n as String }
}
return result
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the `String`
/// that have been divided by characters in a given set.
@warn_unused_result
public func componentsSeparatedByCharactersInSet(
separator: NSCharacterSet
) -> [String] {
// FIXME: two steps due to <rdar://16971181>
let nsa = _ns.componentsSeparatedByCharactersInSet(separator) as NSArray
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
return _convertNSArrayToArray(nsa)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the `String`
/// that have been divided by a given separator.
public func componentsSeparatedByString(separator: String) -> [String] {
let nsa = _ns.componentsSeparatedByString(separator) as NSArray
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
return _convertNSArrayToArray(nsa)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` as a C string
/// using a given encoding.
@warn_unused_result
public func cStringUsingEncoding(encoding: NSStringEncoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cStringUsingEncoding(encoding))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns an `NSData` object containing a representation of
/// the `String` encoded using a given encoding.
@warn_unused_result
public func dataUsingEncoding(
encoding: NSStringEncoding,
allowLossyConversion: Bool = false
) -> NSData? {
return _ns.dataUsingEncoding(
encoding, allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// Returns a string made by normalizing the `String`’s
/// contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// Returns a string made by normalizing the `String`’s
/// contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsingBlock:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(body: (line: String, inout stop: Bool)->()) {
_ns.enumerateLinesUsingBlock {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line: line, stop: &stop_)
if stop_ {
UnsafeMutablePointer<ObjCBool>(stop).memory = true
}
}
}
// - (void)
// enumerateLinguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(NSLinguisticTaggerOptions)opts
// orthography:(NSOrthography *)orthography
// usingBlock:(
// void (^)(
// NSString *tag, NSRange tokenRange,
// NSRange sentenceRange, BOOL *stop)
// )block
/// Performs linguistic analysis on the specified string by
/// enumerating the specific range of the string, providing the
/// Block with the located tags.
public func enumerateLinguisticTagsInRange(
range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTaggerOptions,
orthography: NSOrthography?,
_ body:
(String, Range<Index>, Range<Index>, inout Bool)->()
) {
_ns.enumerateLinguisticTagsInRange(
_toNSRange(range),
scheme: tagScheme,
options: opts,
orthography: orthography != nil ? orthography! : nil
) {
var stop_ = false
body($0, self._range($1), self._range($2), &stop_)
if stop_ {
UnsafeMutablePointer($3).memory = true
}
}
}
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the
/// specified range of the string.
public func enumerateSubstringsInRange(
range: Range<Index>,
options opts:NSStringEnumerationOptions,
_ body: (
substring: String?, substringRange: Range<Index>,
enclosingRange: Range<Index>, inout Bool
)->()
) {
_ns.enumerateSubstringsInRange(_toNSRange(range), options: opts) {
var stop_ = false
body(substring: $0,
substringRange: self._range($1),
enclosingRange: self._range($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).memory = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// Returns the fastest encoding to which the `String` may be
/// converted without loss of information.
public var fastestEncoding: NSStringEncoding {
return _ns.fastestEncoding
}
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message="Use getFileSystemRepresentation on NSURL instead.")
public func fileSystemRepresentation() -> [CChar] {
return _persistCString(_ns.fileSystemRepresentation)!
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(NSStringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver’s contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes(
inout buffer: [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: NSStringEncoding,
options: NSStringEncodingConversionOptions,
range: Range<Index>,
remainingRange leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding,
options: options,
range: _toNSRange(range),
remainingRange: $0)
}
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`’s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
inout buffer: [CChar], maxLength: Int, encoding: NSStringEncoding
) -> Bool {
return _ns.getCString(&buffer, maxLength: min(buffer.count, maxLength),
encoding: encoding)
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message="Use getFileSystemRepresentation on NSURL instead.")
public func getFileSystemRepresentation(
inout buffer: [CChar], maxLength: Int) -> Bool {
return _ns.getFileSystemRepresentation(
&buffer, maxLength: min(buffer.count, maxLength))
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart(
start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
forRange: _toNSRange(forRange))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart(
start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
forRange: _toNSRange(forRange))
}
}
}
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Produces an initialized `NSString` object equivalent to the given
/// `bytes` interpreted in the given `encoding`.
public init? <
S: SequenceType where S.Generator.Element == UInt8
>(
bytes: S, encoding: NSStringEncoding
) {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding) {
self = ns as String
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Produces an initialized `String` object that contains a
/// given number of bytes from a given buffer of bytes interpreted
/// in a given encoding, and optionally frees the buffer. WARNING:
/// this initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutablePointer<Void>, length: Int,
encoding: NSStringEncoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding,
freeWhenDone: flag) {
self = ns as String
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Returns an initialized `String` object that contains a
/// given number of characters from a given array of Unicode
/// characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = NSString(characters: utf16CodeUnits, length: count) as String
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Returns an initialized `String` object that contains a given
/// number of characters from a given array of UTF-16 Code Units
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = NSString(
charactersNoCopy: UnsafeMutablePointer(utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag) as String
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: String,
encoding enc: NSStringEncoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc)
self = ns as String
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: String,
usedEncoding: UnsafeMutablePointer<NSStringEncoding> = nil
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: usedEncoding)
self = ns as String
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOfURL url: NSURL,
encoding enc: NSStringEncoding
) throws {
let ns = try NSString(contentsOfURL: url, encoding: enc)
self = ns as String
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOfURL url: NSURL,
usedEncoding enc: UnsafeMutablePointer<NSStringEncoding> = nil
) throws {
let ns = try NSString(contentsOfURL: url, usedEncoding: enc)
self = ns as String
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
CString: UnsafePointer<CChar>,
encoding enc: NSStringEncoding
) {
if let ns = NSString(CString: CString, encoding: enc) {
self = ns as String
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: NSData, encoding: NSStringEncoding) {
guard let s = NSString(data: data, encoding: encoding) else { return nil }
self = s as String
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: String, _ arguments: CVarArgType...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user’s default locale.
public init(format: String, arguments: [CVarArgType]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: NSLocale?, _ args: CVarArgType...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: NSLocale?, arguments: [CVarArgType]) {
_precondition(
_countFormatSpecifiers(format) <= arguments.count,
"Too many format specifiers (%<letter>) provided for the argument list"
)
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message="Use lastPathComponent on NSURL instead.")
public var lastPathComponent: String {
return _ns.lastPathComponent
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message="Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
return _ns.length
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
@warn_unused_result
public func lengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int {
return _ns.lengthOfBytesUsingEncoding(encoding)
}
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
@warn_unused_result
public func lineRangeForRange(aRange: Range<Index>) -> Range<Index> {
return _range(_ns.lineRangeForRange(_toNSRange(aRange)))
}
// - (NSArray *)
// linguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(NSLinguisticTaggerOptions)opts
// orthography:(NSOrthography *)orthography
// tokenRanges:(NSArray**)tokenRanges
/// Returns an array of linguistic tags for the specified
/// range and requested tags within the receiving string.
@warn_unused_result
public func linguisticTagsInRange(
range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTaggerOptions = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]> = nil // FIXME:Can this be nil?
) -> [String] {
var nsTokenRanges: NSArray? = nil
let result = tokenRanges._withBridgeObject(&nsTokenRanges) {
self._ns.linguisticTagsInRange(
_toNSRange(range), scheme: tagScheme, options: opts,
orthography: orthography != nil ? orthography! : nil, tokenRanges: $0) as NSArray
}
if nsTokenRanges != nil {
tokenRanges._setIfNonNil {
(nsTokenRanges! as [AnyObject]).map {
self._range($0.rangeValue)
}
}
}
return _convertNSArrayToArray(result)
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and a given string using a
/// case-insensitive, localized, comparison.
@warn_unused_result
public
func localizedCaseInsensitiveCompare(aString: String) -> NSComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and a given string using a localized
/// comparison.
@warn_unused_result
public func localizedCompare(aString: String) -> NSComparisonResult {
return _ns.localizedCompare(aString)
}
/// Compares strings as sorted by the Finder.
@warn_unused_result
public func localizedStandardCompare(string: String) -> NSComparisonResult {
return _ns.localizedStandardCompare(string)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercaseString NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedLowercaseString: String {
return _ns.localizedLowercaseString
}
// - (NSString *)lowercaseStringWithLocale:(NSLocale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
@warn_unused_result
public func lowercaseStringWithLocale(locale: NSLocale?) -> String {
return _ns.lowercaseStringWithLocale(locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
@warn_unused_result
public
func maximumLengthOfBytesUsingEncoding(encoding: NSStringEncoding) -> Int {
return _ns.maximumLengthOfBytesUsingEncoding(encoding)
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
@warn_unused_result
public func paragraphRangeForRange(aRange: Range<Index>) -> Range<Index> {
return _range(_ns.paragraphRangeForRange(_toNSRange(aRange)))
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message="Use pathComponents on NSURL instead.")
public var pathComponents: [String] {
return _ns.pathComponents
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`’s extension, if any.
@available(*, unavailable, message="Use pathExtension on NSURL instead.")
public var pathExtension: String {
return _ns.pathExtension
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// Returns a string made by normalizing the `String`’s
/// contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// Returns a string made by normalizing the `String`’s
/// contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
@warn_unused_result
public func propertyList() -> AnyObject {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
@warn_unused_result
public
func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]
}
// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(NSStringCompareOptions)mask
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(NSStringCompareOptions)mask
// range:(NSRange)aRange
/// Finds and returns the range in the `String` of the first
/// character from a given character set found in a given range with
/// given options.
@warn_unused_result
public func rangeOfCharacterFromSet(
aSet: NSCharacterSet,
options mask:NSStringCompareOptions = [],
range aRange: Range<Index>? = nil
)-> Range<Index>? {
return _optionalRange(
_ns.rangeOfCharacterFromSet(
aSet, options: mask,
range: _toNSRange(aRange ?? self.characters.indices)))
}
// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
/// Returns the range in the `String` of the composed
/// character sequence located at a given index.
@warn_unused_result
public
func rangeOfComposedCharacterSequenceAtIndex(anIndex: Index) -> Range<Index> {
return _range(
_ns.rangeOfComposedCharacterSequenceAtIndex(anIndex._utf16Index))
}
// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
/// Returns the range in the string of the composed character
/// sequences for a given range.
@warn_unused_result
public func rangeOfComposedCharacterSequencesForRange(
range: Range<Index>
) -> Range<Index> {
// Theoretically, this will be the identity function. In practice
// I think users will be able to observe differences in the input
// and output ranges due (if nothing else) to locale changes
return _range(
_ns.rangeOfComposedCharacterSequencesForRange(_toNSRange(range)))
}
// - (NSRange)rangeOfString:(NSString *)aString
//
// - (NSRange)
// rangeOfString:(NSString *)aString options:(NSStringCompareOptions)mask
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(NSStringCompareOptions)mask
// range:(NSRange)aRange
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(NSStringCompareOptions)mask
// range:(NSRange)searchRange
// locale:(NSLocale *)locale
/// Finds and returns the range of the first occurrence of a
/// given string within a given range of the `String`, subject to
/// given options, using the specified locale, if any.
@warn_unused_result
public func rangeOfString(
aString: String,
options mask: NSStringCompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: NSLocale? = nil
) -> Range<Index>? {
return _optionalRange(
locale != nil ? _ns.rangeOfString(
aString, options: mask,
range: _toNSRange(searchRange ?? self.characters.indices),
locale: locale
)
: searchRange != nil ? _ns.rangeOfString(
aString, options: mask, range: _toNSRange(searchRange!)
)
: !mask.isEmpty ? _ns.rangeOfString(aString, options: mask)
: _ns.rangeOfString(aString)
)
}
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns `true` if `self` contains `string`, taking the current locale
/// into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardContainsString(string: String) -> Bool {
return _ns.localizedStandardContainsString(string)
}
// - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Finds and returns the range of the first occurrence of a given string,
/// taking the current locale into account. Returns `nil` if the string was
/// not found.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardRangeOfString(string: String) -> Range<Index>? {
return _optionalRange(_ns.localizedStandardRangeOfString(string))
}
// @property NSStringEncoding smallestEncoding;
/// Returns the smallest encoding to which the `String` can
/// be converted without loss of information.
public var smallestEncoding: NSStringEncoding {
return _ns.smallestEncoding
}
// @property NSString *stringByAbbreviatingWithTildeInPath;
/// Returns a new string that replaces the current home
/// directory portion of the current path with a tilde (`~`)
/// character.
@available(*, unavailable, message="Use stringByAbbreviatingWithTildeInPath on NSString instead.")
public var stringByAbbreviatingWithTildeInPath: String {
return _ns.stringByAbbreviatingWithTildeInPath
}
// - (NSString *)
// stringByAddingPercentEncodingWithAllowedCharacters:
// (NSCharacterSet *)allowedCharacters
/// Returns a new string made from the `String` by replacing
/// all characters not in the specified set with percent encoded
/// characters.
@warn_unused_result
public func stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacters: NSCharacterSet
) -> String? {
// FIXME: the documentation states that this method can return nil if the
// transformation is not possible, without going into further details. The
// implementation can only return nil if malloc() returns nil, so in
// practice this is not possible. Still, to be consistent with
// documentation, we declare the method as returning an optional String.
//
// <rdar://problem/17901698> Docs for -[NSString
// stringByAddingPercentEncodingWithAllowedCharacters] don't precisely
// describe when return value is nil
return _ns.stringByAddingPercentEncodingWithAllowedCharacters(
allowedCharacters
)
}
// - (NSString *)
// stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` using a given
/// encoding to determine the percent escapes necessary to convert
/// the `String` into a legal URL string.
@available(*, deprecated, message="Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.")
public func stringByAddingPercentEscapesUsingEncoding(
encoding: NSStringEncoding
) -> String? {
return _ns.stringByAddingPercentEscapesUsingEncoding(encoding)
}
// - (NSString *)stringByAppendingFormat:(NSString *)format, ...
/// Returns a string made by appending to the `String` a
/// string constructed from a given format string and the following
/// arguments.
@warn_unused_result
public func stringByAppendingFormat(
format: String, _ arguments: CVarArgType...
) -> String {
return _ns.stringByAppendingString(
String(format: format, arguments: arguments))
}
// - (NSString *)stringByAppendingPathComponent:(NSString *)aString
/// Returns a new string made by appending to the `String` a given string.
@available(*, unavailable, message="Use URLByAppendingPathComponent on NSURL instead.")
public func stringByAppendingPathComponent(aString: String) -> String {
return _ns.stringByAppendingPathComponent(aString)
}
// - (NSString *)stringByAppendingPathExtension:(NSString *)ext
/// Returns a new string made by appending to the `String` an
/// extension separator followed by a given extension.
@available(*, unavailable, message="Use URLByAppendingPathExtension on NSURL instead.")
public func stringByAppendingPathExtension(ext: String) -> String? {
// FIXME: This method can return nil in practice, for example when self is
// an empty string. OTOH, this is not documented, documentatios says that
// it always returns a string.
//
// <rdar://problem/17902469> -[NSString stringByAppendingPathExtension] can
// return nil
return _ns.stringByAppendingPathExtension(ext)
}
// - (NSString *)stringByAppendingString:(NSString *)aString
/// Returns a new string made by appending a given string to
/// the `String`.
@warn_unused_result
public func stringByAppendingString(aString: String) -> String {
return _ns.stringByAppendingString(aString)
}
// @property NSString* stringByDeletingLastPathComponent;
/// Returns a new string made by deleting the last path
/// component from the `String`, along with any final path
/// separator.
@available(*, unavailable, message="Use URLByDeletingLastPathComponent on NSURL instead.")
public var stringByDeletingLastPathComponent: String {
return _ns.stringByDeletingLastPathComponent
}
// @property NSString* stringByDeletingPathExtension;
/// Returns a new string made by deleting the extension (if
/// any, and only the last) from the `String`.
@available(*, unavailable, message="Use URLByDeletingPathExtension on NSURL instead.")
public var stringByDeletingPathExtension: String {
return _ns.stringByDeletingPathExtension
}
// @property NSString* stringByExpandingTildeInPath;
/// Returns a new string made by expanding the initial
/// component of the `String` to its full path value.
@available(*, unavailable, message="Use stringByExpandingTildeInPath on NSString instead.")
public var stringByExpandingTildeInPath: String {
return _ns.stringByExpandingTildeInPath
}
// - (NSString *)
// stringByFoldingWithOptions:(NSStringCompareOptions)options
// locale:(NSLocale *)locale
/// Returns a string with the given character folding options
/// applied.
@warn_unused_result
public func stringByFoldingWithOptions(
options: NSStringCompareOptions, locale: NSLocale?
) -> String {
return _ns.stringByFoldingWithOptions(options, locale: locale)
}
// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength
// withString:(NSString *)padString
// startingAtIndex:(NSUInteger)padIndex
/// Returns a new string formed from the `String` by either
/// removing characters from the end, or by appending as many
/// occurrences as necessary of a given pad string.
@warn_unused_result
public func stringByPaddingToLength(
newLength: Int, withString padString: String, startingAtIndex padIndex: Int
) -> String {
return _ns.stringByPaddingToLength(
newLength, withString: padString, startingAtIndex: padIndex)
}
// @property NSString* stringByRemovingPercentEncoding;
/// Returns a new string made from the `String` by replacing
/// all percent encoded sequences with the matching UTF-8
/// characters.
public var stringByRemovingPercentEncoding: String? {
return _ns.stringByRemovingPercentEncoding
}
// - (NSString *)
// stringByReplacingCharactersInRange:(NSRange)range
// withString:(NSString *)replacement
/// Returns a new string in which the characters in a
/// specified range of the `String` are replaced by a given string.
@warn_unused_result
public func stringByReplacingCharactersInRange(
range: Range<Index>, withString replacement: String
) -> String {
return _ns.stringByReplacingCharactersInRange(
_toNSRange(range), withString: replacement)
}
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
//
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
// options:(NSStringCompareOptions)options
// range:(NSRange)searchRange
/// Returns a new string in which all occurrences of a target
/// string in a specified range of the `String` are replaced by
/// another given string.
@warn_unused_result
public func stringByReplacingOccurrencesOfString(
target: String,
withString replacement: String,
options: NSStringCompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
return (searchRange != nil) || (!options.isEmpty)
? _ns.stringByReplacingOccurrencesOfString(
target,
withString: replacement, options: options,
range: _toNSRange(searchRange ?? self.characters.indices)
)
: _ns.stringByReplacingOccurrencesOfString(target, withString: replacement)
}
// - (NSString *)
// stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a new string made by replacing in the `String`
/// all percent escapes with the matching characters as determined
/// by a given encoding.
@available(*, deprecated, message="Use stringByRemovingPercentEncoding instead, which always uses the recommended UTF-8 encoding.")
public func stringByReplacingPercentEscapesUsingEncoding(
encoding: NSStringEncoding
) -> String? {
return _ns.stringByReplacingPercentEscapesUsingEncoding(encoding)
}
// @property NSString* stringByResolvingSymlinksInPath;
/// Returns a new string made from the `String` by resolving
/// all symbolic links and standardizing path.
@available(*, unavailable, message="Use URLByResolvingSymlinksInPath on NSURL instead.")
public var stringByResolvingSymlinksInPath: String {
return _ns.stringByResolvingSymlinksInPath
}
// @property NSString* stringByStandardizingPath;
/// Returns a new string made by removing extraneous path
/// components from the `String`.
@available(*, unavailable, message="Use URLByStandardizingPath on NSURL instead.")
public var stringByStandardizingPath: String {
return _ns.stringByStandardizingPath
}
// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
/// Returns a new string made by removing from both ends of
/// the `String` characters contained in a given character set.
@warn_unused_result
public func stringByTrimmingCharactersInSet(set: NSCharacterSet) -> String {
return _ns.stringByTrimmingCharactersInSet(set)
}
// - (NSArray *)stringsByAppendingPaths:(NSArray *)paths
/// Returns an array of strings made by separately appending
/// to the `String` each string in in a given array.
@available(*, unavailable, message="map over paths with URLByAppendingPathComponent instead.")
public func stringsByAppendingPaths(paths: [String]) -> [String] {
return _ns.stringsByAppendingPaths(paths)
}
// - (NSString *)substringFromIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` from the one at a given index to the end.
@warn_unused_result
public func substringFromIndex(index: Index) -> String {
return _ns.substringFromIndex(index._utf16Index)
}
// - (NSString *)substringToIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` up to, but not including, the one at a given index.
@warn_unused_result
public func substringToIndex(index: Index) -> String {
return _ns.substringToIndex(index._utf16Index)
}
// - (NSString *)substringWithRange:(NSRange)aRange
/// Returns a string object containing the characters of the
/// `String` that lie within a given range.
@warn_unused_result
public func substringWithRange(aRange: Range<Index>) -> String {
return _ns.substringWithRange(_toNSRange(aRange))
}
// @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
/// An uppercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedUppercaseString: String {
return _ns.localizedUppercaseString as String
}
// - (NSString *)uppercaseStringWithLocale:(NSLocale *)locale
/// Returns a version of the string with all letters
/// converted to uppercase, taking into account the specified
/// locale.
@warn_unused_result
public func uppercaseStringWithLocale(locale: NSLocale?) -> String {
return _ns.uppercaseStringWithLocale(locale)
}
//===--- Omitted due to redundancy with "utf8" property -----------------===//
// - (const char *)UTF8String
// - (BOOL)
// writeToFile:(NSString *)path
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to a file at a given
/// path using a given encoding.
public func writeToFile(
path: String, atomically useAuxiliaryFile:Bool,
encoding enc: NSStringEncoding
) throws {
try self._ns.writeToFile(
path, atomically: useAuxiliaryFile, encoding: enc)
}
// - (BOOL)
// writeToURL:(NSURL *)url
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to the URL specified
/// by url using the specified encoding.
public func writeToURL(
url: NSURL, atomically useAuxiliaryFile: Bool,
encoding enc: NSStringEncoding
) throws {
try self._ns.writeToURL(
url, atomically: useAuxiliaryFile, encoding: enc)
}
// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0);
/// Perform string transliteration.
@warn_unused_result
@available(OSX 10.11, iOS 9.0, *)
public func stringByApplyingTransform(
transform: String, reverse: Bool
) -> String? {
return _ns.stringByApplyingTransform(transform, reverse: reverse)
}
//===--- From the 10.10 release notes; not in public documentation ------===//
// No need to make these unavailable on earlier OSes, since they can
// forward trivially to rangeOfString.
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-sensitive, non-literal search.
///
/// Equivalent to `self.rangeOfString(other) != nil`
@warn_unused_result
public func containsString(other: String) -> Bool {
let r = self.rangeOfString(other) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.containsString(other))
}
return r
}
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-insensitive, non-literal search, taking into
/// account the current locale.
///
/// Locale-independent case-insensitive operation, and other needs,
/// can be achieved by calling
/// `rangeOfString(_:options:_,range:_locale:_)`.
///
/// Equivalent to
///
/// self.rangeOfString(
/// other, options: .CaseInsensitiveSearch,
/// locale: NSLocale.currentLocale()) != nil
@warn_unused_result
public func localizedCaseInsensitiveContainsString(other: String) -> Bool {
let r = self.rangeOfString(
other, options: .CaseInsensitiveSearch, locale: NSLocale.currentLocale()
) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.localizedCaseInsensitiveContainsString(other))
}
return r
}
}
| apache-2.0 | ca6927883626be988c5ddea37c5cef32 | 34.061942 | 311 | 0.680171 | 4.838813 | false | false | false | false |
february29/Learning | swift/Fch_Contact/Fch_Contact/AppClasses/AppToolBox/Theme.swift | 1 | 9496 | //
// Theme.swift
// Fch_Contact
//
// Created by bai on 2018/1/30.
// Copyright © 2018年 北京仙指信息技术有限公司. All rights reserved.
//
import Foundation
//import RxCocoa
import RxSwift
import HandyJSON
enum Theme:String,HandyJSONEnum{
case white
case black
case green
case red
case blue
case purple
case pink
}
enum ThemeColorType {
case navBar//导航栏背景
case navBarTitle//导航栏标题
case navBarBtn//导航栏按钮颜色
case background//view背景
case tableBackground//主列表背景
case leftTableBackground//菜单列表背景 暂时未用
case primary//lable buttom等
case secondary//tablesection
case selectedCell
}
func rgb(_ hexString: String) -> UIColor? {
return UIColor(hexString: hexString)
}
func rgba(_ hexString: String,_ alpha: CGFloat) -> UIColor? {
return UIColor(hexString: hexString, alpha: alpha)
}
extension Theme {
var colors:[UIColor]{
switch self {
case .white:
return [rgb("ffffff")!,
rgb("000000")!,
BGlobalRedColor(),
rgb("ffffff")!,
UIColor.white,
rgba("333333", 0.8)!,
rgba("222222", 0.8)!,
BRGBColor(r: 236, g: 236, b: 236, a:1)]
case .black:
return [rgb("313231")!,
rgb("cccccc")!,
rgb("ffffff")!,
rgb("313231")!,
rgb("333333")!,
rgba("313231", 0.8)!,
rgba("cccccc", 0.8)!,
rgba("222222", 1)!]
case .blue:
return [rgb("0291D4")!,
rgb("ffffff")!,
rgb("ffffff")!,
rgb("ffffff")!,
UIColor.white,
rgba("0291D4", 0.8)!,
rgba("0291D4", 0.8)!,
BRGBColor(r: 236, g: 236, b: 236, a:1)]
case .purple:
return [rgb("6c16c7")!,
rgb("ffffff")!,
rgb("ffffff")!,
rgb("ffffff")!,
UIColor.white,
rgba("6c16c7", 0.8)!,
rgba("6c16c7", 0.8)!,
BRGBColor(r: 236, g: 236, b: 236, a:1)]
case .red:
return [rgb("D2373B")!,
rgb("ffffff")!,rgb("ffffff")!,
rgb("ffffff")!,
UIColor.white,
rgba("D2373B", 0.8)!,
rgba("D2373B", 0.8)!,
BRGBColor(r: 236, g: 236, b: 236, a:1)]
case .green:
return [rgb("01BD70")!,
rgb("ffffff")!,
rgb("ffffff")!,
rgb("ffffff")!,
UIColor.white,
rgba("333333", 0.8)!,
rgba("01BD70", 0.8)!,
BRGBColor(r: 236, g: 236, b: 236, a:1)]
case .pink:
return [rgb("E52D7C")!,
rgb("ffffff")!,
rgb("ffffff")!,
rgb("ffffff")!,
UIColor.white,
rgba("333333", 0.8)!,
rgba("E52D7C", 0.8)!,
BRGBColor(r: 236, g: 236, b: 236, a:1)]
}
}
var displayName: String {
switch self {
case .white:
return BLocalizedString(key: "ThemeWhite")
case .black:
return BLocalizedString(key: "ThemeBlack")
case .blue:
return BLocalizedString(key: "ThemeBlue")
case .red:
return BLocalizedString(key: "ThemeRed")
case .purple:
return BLocalizedString(key: "ThemePurple")
case .pink:
return BLocalizedString(key: "ThemePink")
case .green:
return BLocalizedString(key: "ThemeGreen")
}
}
}
class ColorCenter {
static let shared = ColorCenter()
let navBar = Variable(UIColor.clear)
let navBarTitle = Variable(UIColor.clear)
let navBarBtn = Variable(UIColor.clear)
let primary = Variable(UIColor.clear)
let secondary = Variable(UIColor.clear)
let background = Variable(UIColor.clear)
let tableBackground = Variable(UIColor.clear)
let leftTableBackground = Variable(UIColor.clear)
let selectedCell = Variable(UIColor.clear)
let themeName = Variable("");
var theme: Theme = .white {
didSet {
navBar.value = theme.colors[0]
navBarTitle.value = theme.colors[1]
navBarBtn.value = theme.colors[2]
background.value = theme.colors[3]
tableBackground.value = theme.colors[4]
leftTableBackground.value = theme.colors[5]
primary.value = theme.colors[6]
secondary.value = theme.colors[7]
selectedCell.value = theme == .black ? rgb("151515")! : rgb("e0e0e0")!
themeName.value = theme.displayName;
}
}
func colorVariable(with type: ThemeColorType) -> Variable<UIColor> {
switch type {
case .navBar:
return navBar
case .navBarTitle:
return navBarTitle
case .navBarBtn:
return navBarBtn
case .primary:
return primary
case .secondary:
return secondary
case .background:
return background
case .tableBackground:
return tableBackground
case .leftTableBackground:
return leftTableBackground
case .selectedCell:
return selectedCell
}
}
}
extension UINavigationBar {
func setBarTintColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.barTintColor = color
})
}
func setContentColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.tintColor = color
let attr: [NSAttributedStringKey:Any] = [
NSAttributedStringKey.font: UIFont.systemFont(ofSize: 18),
NSAttributedStringKey.foregroundColor: color
]
self.titleTextAttributes = attr
})
}
}
extension UIView {
func setBackgroundColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self] (color) in
self.backgroundColor = color
})
}
func setTintColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.tintColor = color
})
}
}
extension UILabel {
func setTextColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.textColor = color
})
}
// func setTextThemeName() {
// _ = ColorCenter.shared.themeName.asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](name) in
// self.text = name;
// })
// }
}
extension UIButton {
func setTitleColor(_ color: ThemeColorType, forState: UIControlState = .normal) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.setTitleColor(color, for: forState)
})
}
}
extension UIBarButtonItem {
func setTintColor(_ color: ThemeColorType, forState: UIControlState = .normal) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.tintColor = color;
})
}
}
extension UITableView {
func setSeparatorColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.separatorColor = color.withAlphaComponent(0.25);
})
}
func setSectionIndexColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.sectionIndexColor = color;
})
}
}
extension UITextField {
func setTextColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.textColor = color
})
}
}
extension UIActivityIndicatorView {
func setColor(_ color: ThemeColorType) {
_ = ColorCenter.shared.colorVariable(with: color).asObservable().takeUntil(rx.deallocated).subscribe(onNext: { [unowned self](color) in
self.color = color
})
}
}
| mit | 2a2b90aeef67a6424f5bfeedaefaa691 | 29.417476 | 144 | 0.539951 | 4.573723 | false | false | false | false |
ijovi23/JvPunchIO | JvPunchIO-Recorder/JvPunchIO-Recorder/View/PRAddRecordView.swift | 1 | 1796 | //
// PRAddRecordView.swift
// JvPunchIO-Recorder
//
// Created by Jovi Du on 25/10/2016.
// Copyright © 2016 org.Jovistudio. All rights reserved.
//
import UIKit
protocol PRAddRecordViewDelegate: class {
func addRecordView(_ addRecordView: PRAddRecordView, didAdd date: Date)
}
class PRAddRecordView: UIView {
weak var delegate: PRAddRecordViewDelegate?
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var btnClose: UIButton!
@IBOutlet weak var pickerDate: UIDatePicker!
@IBOutlet weak var btnAdd: UIButton!
func show() {
if superview == nil {
UIApplication.shared.keyWindow?.addSubview(self)
}
pickerDate.setDate(Date(), animated: false)
let sWidth = bounds.size.width
let sHeight = bounds.size.height
self.mainView.center = CGPoint(x: (sWidth / 2), y: (sHeight + mainView.bounds.height / 2))
self.alpha = 0
UIView.animate(withDuration: 0.2) {
self.mainView.center = CGPoint(x: (sWidth / 2), y: (sHeight / 2))
self.alpha = 1
}
}
func hide() {
let sWidth = bounds.size.width
let sHeight = bounds.size.height
UIView.animate(withDuration: 0.2, animations: {
self.mainView.center = CGPoint(x: (sWidth / 2), y: (sHeight + self.mainView.bounds.height / 2))
self.alpha = 0
})
{ (finished) in
self.removeFromSuperview()
}
}
@IBAction func btnClosePressed(_ sender: UIButton) {
hide()
}
@IBAction func btnAddPressed(_ sender: UIButton) {
delegate?.addRecordView(self, didAdd: pickerDate.date)
hide()
}
}
| mit | d9171cdbcaf069f0c52a68a840154024 | 24.642857 | 107 | 0.577716 | 4.193925 | false | false | false | false |
kmalkic/LazyKit | LazyKit/Classes/LazyConstraintOptions.swift | 1 | 2887 | //
// LazyConstraintOptions.swift
// LazyKit
//
// Created by Kevin Malkic on 17/01/2016.
// Copyright © 2016 Kevin Malkic. All rights reserved.
//
import UIKit
//MARK: - Layout constraints options
///Structure to map visual format constraints
public struct VisualFormatConstraintOptions {
/**
A string that identifies the set of constraints.
*/
public var identifier: String?
/**
The format specification for the constraints. For more information, see Visual Format Language in Auto Layout Guide.
*/
public let string: String
/**
Options describing the attribute and the direction of layout for all objects in the visual format string.
*/
public let options: NSLayoutFormatOptions
/**
Constructor
*/
public init(identifier: String? = nil, string: String, options: NSLayoutFormatOptions = NSLayoutFormatOptions(rawValue: 0)) {
self.identifier = identifier
self.string = string
self.options = options
}
}
///Structure to map layout constraints
public struct ConstraintOptions {
/**
A string that identifies the layout.
*/
public var identifier: String?
/**
A string that identifies the element for the left side of the constraint.
*/
public let identifier1: String
/**
A string that identifies the element for the right side of the constraint.
*/
public let identifier2: String?
/**
The attribute of the view for the left side of the constraint.
*/
public let attribute1: NSLayoutAttribute
/**
The attribute of the view for the right side of the constraint.
*/
public let attribute2: NSLayoutAttribute
/**
The relationship between the left side of the constraint and the right side of the constraint.
*/
public let relatedBy: NSLayoutRelation
/**
The constant multiplied with the attribute on the right side of the constraint as part of getting the modified attribute.
*/
public let multiplier: CGFloat
/**
The constant added to the multiplied attribute value on the right side of the constraint to yield the final modified attribute.
*/
public let constant: CGFloat
/**
Constructor
*/
public init(identifier: String? = nil, itemIdentifier identifier1: String, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItemIdentifier identifier2: String? = nil, toSuperview useSuperview: Bool = false, attribute attr2: NSLayoutAttribute, multiplier: CGFloat, constant c: CGFloat) {
self.identifier = identifier
self.identifier1 = identifier1
self.identifier2 = (useSuperview) ? "superview" : identifier2
self.attribute1 = attr1
self.attribute2 = attr2
self.relatedBy = relation
self.multiplier = multiplier
self.constant = c
}
}
| mit | ad536db61c8bfe30f1a0bb34bc07b200 | 31.066667 | 314 | 0.688496 | 4.924915 | false | false | false | false |
Thongpak21/NongBeer-MVVM-iOS-Demo | NongBeer/Classes/History/ViewModel/HistoryViewModel.swift | 1 | 1595 | //
// HistoryViewModel.swift
// NongBeer
//
// Created by Thongpak on 4/11/2560 BE.
// Copyright © 2560 Thongpak. All rights reserved.
//
import Foundation
import IGListKit
protocol HistoryViewModelProtocol {
var history: [IGListDiffable] {get set}
func getListHistoryService()
func getListHistoryHandler() -> APIRequest.completionHandler
var isPullToRefresh: Bool { get set }
}
class HistoryViewModel: BaseViewModel, HistoryViewModelProtocol {
var history = [LoadingType.refresh.rawValue as IGListDiffable]
var page: Int? = 0
var isPullToRefresh = false
func getListHistoryService() {
let router = Router.getHistory(page: page!)
_ = APIRequest.request(withRouter: router, withHandler: getListHistoryHandler())
}
func getListHistoryHandler() -> APIRequest.completionHandler {
return { [weak self] (response, error) in
if let response = response as? HistoryModel {
self?.page = response.nextOrderIndex
if self?.history.contains(where: { $0 as? String == LoadingType.refresh.rawValue }) == true {
self?.history.remove(at: 0)
}
if self?.history.contains(where: { $0 as? String == LoadingType.loadmore.rawValue }) == true {
self?.history.removeLast()
}
self?.history.append(response)
self?.delegate?.onDataDidLoad()
} else {
self?.delegate?.onDataDidLoad()
}
}
}
}
| apache-2.0 | 6358705182fab1dfd10e269fcbb1a0a9 | 33.652174 | 110 | 0.600376 | 4.744048 | false | false | false | false |
vitkuzmenko/NetworkManager | Source/NetworkManager/DictionarySerializer.swift | 1 | 2805 | //
// DictionarySerializer.swift
// Locals
//
// Created by Vitaliy Kuzmenko on 02/08/16.
// Copyright © 2016 Locals. All rights reserved.
//
import Foundation
extension String {
var URLEncode: String {
var set = CharacterSet.alphanumerics
set.insert(charactersIn: "_.-~")
return addingPercentEncoding(withAllowedCharacters: set) ?? self
}
}
open class DictionarySerializer {
var dict: [String: Any]
public init(dict: [String: Any]) {
self.dict = dict
}
open func getParametersInFormEncodedString() -> String {
return serialize(dict: dict)
}
open func serialize(dict: [String: Any], nested: String? = nil) -> String {
var strings: [String] = []
for (key, value) in dict {
var string = key
if let nested = nested {
string = String(format: "%@[%@]", nested, key)
}
string = serialize(value: value, withString: string, nested: nested)
strings.append(string)
}
return strings.joined(separator: "&")
}
open func serialize(array: [Any], nested: String? = nil) -> String {
var strings: [String] = []
for value in array {
var string = ""
if let nested = nested {
string = String(format: "%@[]", nested)
}
string = serialize(value: value, withString: string, nested: nested)
strings.append(string)
}
return strings.joined(separator: "&")
}
open func serialize(value: Any, withString string: String, nested: String? = nil) -> String {
var string = string
if let value = value as? String {
string = String(format: "%@=%@", string, value.URLEncode)
} else if let value = value as? NSNumber {
string = String(format: "%@=%@", string, value.stringValue.URLEncode)
} else if let value = value as? [String: Any] {
string = serialize(dict: value, nested: string)
} else if let value = value as? [Any] {
string = serialize(array: value, nested: string)
}
return string
}
open func flatKeyValue() -> [String: String] {
let string = serialize(dict: dict)
let components = string.components(separatedBy: "&")
var keyValues: [String: String] = [:]
for item in components {
let components = item.components(separatedBy: "=")
if components.count != 2 { continue }
keyValues[components[0]] = components[1]
}
return keyValues
}
}
| mit | 000f03fe386c23ce8e2099b18ccc4325 | 27.323232 | 97 | 0.528887 | 4.704698 | false | false | false | false |
toshiapp/toshi-ios-client | Toshi/Controllers/Dapps/DappsViewController.swift | 1 | 20586 | // Copyright (c) 2018 Token Browser, Inc
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import SweetFoundation
import UIKit
import SweetUIKit
enum BrowseContentSection: Int {
case topRatedApps
case featuredDapps
case topRatedPublicUsers
case latestPublicUsers
var title: String {
switch self {
case .topRatedApps:
return Localized.browse_top_rated_apps
case .featuredDapps:
return Localized.browse_featured_dapps
case .topRatedPublicUsers:
return Localized.browse_top_rated_public_users
case .latestPublicUsers:
return Localized.browse_latest_public_users
}
}
}
protocol BrowseableItem {
var nameForBrowseAndSearch: String { get }
var descriptionForSearch: String? { get }
var avatarPath: String { get }
var shouldShowRating: Bool { get }
var rating: Float? { get }
}
final class DappsViewController: UIViewController {
// We dequeue separate cells for generic UITableViewCell with text and one which has added custom subview
// so we do not have to remove those subview on reuse of a UITableViewCell instance
private let buttonCellReuseIdentifier = "ButtonCellReuseIdentifier"
private let genericCellReuseIdentifier = "GenericCellReuseIdentifier"
override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return .fade
}
var statusBarStyle: UIStatusBarStyle = .lightContent {
didSet {
UIView.animate(withDuration: 0.5) {
self.setNeedsStatusBarAppearanceUpdate()
}
}
}
var percentage: CGFloat = 0.0
override var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
private let defaultSectionHeaderHeight: CGFloat = 50
private let searchedResultsSectionHeaderHeight: CGFloat = 24
private let defaultTableViewBottomInset: CGFloat = -21
private var reloadTimer: Timer?
private var shouldResetContentOffset = false
lazy var activityIndicator: UIActivityIndicatorView = defaultActivityIndicator()
private lazy var dataSource: DappsDataSource = {
let dataSource = DappsDataSource(mode: .frontPage)
dataSource.delegate = self
return dataSource
}()
private lazy var headerView: DappsTableHeaderView = {
let headerView = DappsTableHeaderView(frame: CGRect.zero, delegate: self)
return headerView
}()
private lazy var tableView: UITableView = {
let view = UITableView(frame: CGRect.zero, style: .grouped)
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = Theme.viewBackgroundColor
BasicTableViewCell.register(in: view)
view.delegate = self
view.dataSource = self
view.contentInset.top = -headerView.sizeRange.lowerBound
view.scrollIndicatorInsets.top = -headerView.sizeRange.lowerBound
view.sectionFooterHeight = 0.0
view.contentInset.bottom = defaultTableViewBottomInset
view.scrollIndicatorInsets.bottom = defaultTableViewBottomInset
view.estimatedRowHeight = 98
view.alwaysBounceVertical = true
BasicTableViewCell.register(in: view)
view.register(UITableViewCell.self, forCellReuseIdentifier: buttonCellReuseIdentifier)
view.register(UITableViewCell.self, forCellReuseIdentifier: genericCellReuseIdentifier)
view.separatorStyle = .none
return view
}()
private lazy var seeAllDappsButton: ActionButton = {
let button = ActionButton(margin: .defaultMargin)
button.addTarget(self,
action: #selector(didTapSeeAllDappsButton(_:)),
for: .touchUpInside)
button.title = Localized.dapps_see_all_button_title
return button
}()
private lazy var searchResultsTableView: UITableView = {
let view = UITableView(frame: CGRect.zero, style: .grouped)
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = Theme.viewBackgroundColor
BasicTableViewCell.register(in: view)
view.delegate = self
view.dataSource = self
view.sectionFooterHeight = 0.0
view.contentInset.bottom = defaultTableViewBottomInset
view.scrollIndicatorInsets.bottom = defaultTableViewBottomInset
view.estimatedRowHeight = 98
view.alwaysBounceVertical = true
view.register(UITableViewCell.self, forCellReuseIdentifier: buttonCellReuseIdentifier)
view.register(UITableViewCell.self, forCellReuseIdentifier: genericCellReuseIdentifier)
view.separatorStyle = .none
return view
}()
var scrollViewBottomInset: CGFloat = 0
override func viewDidLoad() {
super.viewDidLoad()
registerForKeyboardNotifications()
addSubviewsAndConstraints()
setupActivityIndicator()
}
private func addSubviewsAndConstraints() {
view.addSubview(tableView)
view.addSubview(headerView)
headerView.top(to: layoutGuide(), offset: -UIApplication.shared.statusBarFrame.height)
headerView.left(to: view)
headerView.right(to: view)
tableView.top(to: layoutGuide(), offset: -UIApplication.shared.statusBarFrame.height)
tableView.left(to: view)
tableView.right(to: view)
tableView.bottom(to: view)
view.addSubview(searchResultsTableView)
searchResultsTableView.topToBottom(of: headerView)
searchResultsTableView.edgesToSuperview(excluding: .top)
searchResultsTableView.alpha = 0
view.layoutIfNeeded()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: false)
dataSource.fetchItems()
}
private func showResults(_ apps: [BrowseableItem]?, in section: BrowseContentSection, _ error: Error? = nil) {
if let error = error {
let alertController = UIAlertController.errorAlert(error as NSError)
Navigator.presentModally(alertController)
}
}
private func avatar(for indexPath: IndexPath, completion: @escaping ((UIImage?) -> Void)) {
guard let item = dataSource.itemAtIndexPath(indexPath), let avatarPath = item.itemIconPath else {
completion(nil)
return
}
AvatarManager.shared.avatar(for: avatarPath, completion: { image, _ in
completion(image)
})
}
func rescheduleReload() {
dataSource.cancelFetch()
reloadTimer?.invalidate()
reloadTimer = nil
reloadTimer = Timer.scheduledTimer(withTimeInterval: 0.2, repeats: false) { [weak self] _ in
guard let strongSelf = self else { return }
strongSelf.dataSource.reloadWithSearchText(strongSelf.headerView.searchTextField.currentOrEmptyText)
}
}
@objc private func didTapSeeAllDappsButton(_ button: UIButton) {
let categoryDappsViewController = DappsListViewController(name: Localized.dapps_all_list_title)
Navigator.push(categoryDappsViewController)
}
}
extension DappsViewController: DappsDataSourceDelegate {
func dappsDataSourcedidReload(_ dataSource: DappsDataSource) {
hideActivityIndicator()
if shouldResetContentOffset {
tableView.setContentOffset(CGPoint(x: 0, y: -300), animated: false)
shouldResetContentOffset = false
}
tableView.reloadData()
searchResultsTableView.reloadData()
}
}
extension DappsViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.numberOfSections
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.numberOfItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let item = dataSource.itemAtIndexPath(indexPath) else {
fatalError("Can't find an item while dequeuing cell")
}
switch item.type {
case .goToUrl:
let cell = tableView.dequeueReusableCell(withIdentifier: genericCellReuseIdentifier, for: indexPath)
cell.selectionStyle = .none
cell.textLabel?.text = item.displayTitle
cell.textLabel?.textColor = Theme.tintColor
return cell
case .searchWithGoogle:
let cell = tableView.dequeueReusableCell(withIdentifier: genericCellReuseIdentifier, for: indexPath)
cell.selectionStyle = .none
let googleText = " – \(Localized.dapps_search_with_google_section_title)"
let text = String.contentsOrEmpty(for: item.displayTitle) + googleText
let attributedString = NSMutableAttributedString(string: text)
attributedString.addAttribute(.font, value: Theme.preferredRegularTiny(), range: NSRange(location: 0, length: attributedString.length))
if let range = text.range(of: googleText) {
attributedString.addAttribute(.foregroundColor, value: Theme.placeholderTextColor, range: NSRange(location: range.lowerBound.encodedOffset, length: googleText.count))
}
cell.textLabel?.attributedText = attributedString
return cell
case .dappFront:
let cellData = TableCellData(title: item.displayTitle, leftImage: ImageAsset.collectible_placeholder, leftImagePath: item.itemIconPath, description: item.displayDetails)
let configurator = CellConfigurator()
guard let cell = tableView.dequeueReusableCell(withIdentifier: configurator.cellIdentifier(for: cellData.components), for: indexPath) as? BasicTableViewCell else { return UITableViewCell() }
configurator.configureCell(cell, with: cellData)
cell.showSeparator(leftInset: 100, rightInset: .spacingx3)
return cell
case .dappSearched:
let cellData = TableCellData(title: item.displayTitle, subtitle: item.dapp?.url.absoluteString, leftImagePath: item.itemIconPath)
let configurator = CellConfigurator()
guard let cell = tableView.dequeueReusableCell(withIdentifier: configurator.cellIdentifier(for: cellData.components), for: indexPath) as? BasicTableViewCell else { return UITableViewCell() }
configurator.configureCell(cell, with: cellData)
cell.leftImageView.layer.cornerRadius = 5
cell.titleTextField.setDynamicFontBlock = { [weak cell] in
guard let strongCell = cell else { return }
strongCell.titleTextField.font = Theme.preferredSemibold()
}
return cell
case .seeAll:
let cell = tableView.dequeueReusableCell(withIdentifier: buttonCellReuseIdentifier, for: indexPath)
cell.selectionStyle = .none
cell.contentView.addSubview(seeAllDappsButton)
seeAllDappsButton.edgesToSuperview(insets: UIEdgeInsets(top: .spacingx8,
left: .defaultMargin,
bottom: .spacingx8,
right: -.defaultMargin))
return cell
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let sectionData = dataSource.section(at: section) else { return nil }
let header = DappsSectionHeaderView(delegate: self)
header.backgroundColor = dataSource.mode == .frontPage ? Theme.viewBackgroundColor : Theme.lighterGreyTextColor
header.titleLabel.textColor = dataSource.mode == .frontPage ? Theme.greyTextColor : Theme.lightGreyTextColor
header.actionButton.setTitle(Localized.dapps_see_more_button_title, for: .normal)
header.tag = section
header.titleLabel.text = sectionData.name?.uppercased()
header.actionButton.isHidden = sectionData.categoryId == nil
return header
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch dataSource.mode {
case .frontPage:
return defaultSectionHeaderHeight
case .allOrFiltered:
guard let sectionData = dataSource.section(at: section), sectionData.name != nil else { return 0 }
return searchedResultsSectionHeaderHeight
}
}
}
extension DappsViewController: DappsSectionHeaderViewDelegate {
func dappsSectionHeaderViewDidReceiveActionButtonEvent(_ sectionHeaderView: DappsSectionHeaderView) {
guard let section = dataSource.section(at: sectionHeaderView.tag) else { return }
guard let categoryId = section.categoryId else { return }
let categoryDappsViewController = DappsListViewController(categoryId: categoryId, name: section.name)
Navigator.push(categoryDappsViewController)
}
}
extension DappsViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let item = dataSource.itemAtIndexPath(indexPath) else { return }
let searchBaseUrl = "https://www.google.com/search?q="
switch item.type {
case .goToUrl:
guard
let searchText = item.displayTitle,
let possibleUrlString = searchText.asPossibleURLString,
let url = URL(string: possibleUrlString)
else { return }
let sofaController = SOFAWebController()
sofaController.load(url: url)
Navigator.presentModally(sofaController)
case .dappFront:
guard let dapp = item.dapp else { return }
let controller = DappViewController(with: dapp, categoriesInfo: dataSource.categoriesInfo)
Navigator.push(controller)
case .dappSearched:
guard let dapp = item.dapp else { return }
let sofaWebController = SOFAWebController()
sofaWebController.delegate = self
sofaWebController.load(url: dapp.urlToLoad)
Navigator.presentModally(sofaWebController)
case .searchWithGoogle:
guard
let searchText = item.displayTitle,
let escapedSearchText = searchText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed),
let url = URL(string: searchBaseUrl.appending(escapedSearchText))
else { return }
let sofaController = SOFAWebController()
sofaController.load(url: url)
Navigator.presentModally(sofaController)
case .seeAll:
// We ignore selection as the cell contains action button which touch event do we process
break
}
}
}
extension DappsViewController: SOFAWebControllerDelegate {
func sofaWebControllerWillFinish(_ sofaWebController: SOFAWebController) {
headerView.cancelSearch()
}
}
extension DappsViewController: UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// We should ignore scrolling of front page results tableView which is behind and current mode is search mode, so header is not broken during the search
guard scrollView != searchResultsTableView && searchResultsTableView.alpha < 1 else { return }
let percentage = scrollView.contentOffset.y.map(from: headerView.sizeRange, to: 0...1).clamp(to: -2...1)
guard self.percentage != percentage else { return }
headerView.didScroll(to: percentage)
adjustContentSizeOn(scrollView: scrollView)
self.percentage = percentage
if percentage < 0.90 {
statusBarStyle = UIStatusBarStyle.lightContent
} else {
statusBarStyle = UIStatusBarStyle.default
}
}
private func adjustContentSizeOn(scrollView: UIScrollView) {
var safeArea: CGFloat = 0
if #available(iOS 11.0, *) {
safeArea = scrollView.safeAreaInsets.bottom
}
let height = scrollView.frame.height
let insetBottom = scrollView.contentInset.bottom
let contentOffset = headerView.sizeRange.upperBound
let totalInset = abs(contentOffset - safeArea)
let contentSpace = height - totalInset - insetBottom
if scrollView.contentSize.height > 0 && scrollView.contentSize.height < contentSpace {
scrollView.contentSize.height = contentSpace
}
}
func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
guard headerView.sizeRange.contains(targetContentOffset.pointee.y) else { return}
let centerOfRange = headerView.sizeRange.lowerBound + ((headerView.sizeRange.upperBound - headerView.sizeRange.lowerBound) / 2)
targetContentOffset.pointee.y = targetContentOffset.pointee.y < centerOfRange ? headerView.sizeRange.lowerBound : headerView.sizeRange.upperBound
}
}
extension DappsViewController: DappsSearchHeaderViewDelegate {
func didRequireCollapsedState(_ headerView: DappsTableHeaderView) {
showActivityIndicator()
dataSource.queryData.isSearching = true
view.layoutIfNeeded()
headerView.adjustNonAnimatedProperties(to: headerView.collapsedStateScrollPercentage)
UIView.animate(withDuration: 0.3) {
self.searchResultsTableView.alpha = 1
self.statusBarStyle = UIStatusBarStyle.default
self.headerView.adjustAnimatedProperties(to: self.headerView.collapsedStateScrollPercentage)
self.view.layoutIfNeeded()
}
}
func didRequireDefaultState(_ headerView: DappsTableHeaderView) {
shouldResetContentOffset = true
if dataSource.queryData.isSearching && Navigator.reachabilityStatus != .notReachable {
showActivityIndicator()
}
dataSource.cancelSearch()
view.layoutIfNeeded()
headerView.adjustNonAnimatedProperties(to: headerView.expandedStateScrollPercentage)
UIView.animate(withDuration: 0.3) {
self.searchResultsTableView.alpha = 0
self.statusBarStyle = UIStatusBarStyle.lightContent
self.headerView.adjustAnimatedProperties(to: self.headerView.expandedStateScrollPercentage)
self.view.layoutIfNeeded()
}
}
func dappsSearchDidUpdateSearchText(_ headerView: DappsTableHeaderView, searchText: String) {
dataSource.adjustToSearchText(searchText)
rescheduleReload()
}
}
// MARK: - Keyboard Adjustable
extension DappsViewController: KeyboardAdjustable {
var scrollView: UIScrollView {
return searchResultsTableView
}
var keyboardWillShowSelector: Selector {
return #selector(keyboardShownNotificationReceived(_:))
}
var keyboardWillHideSelector: Selector {
return #selector(keyboardHiddenNotificationReceived(_:))
}
@objc private func keyboardShownNotificationReceived(_ notification: NSNotification) {
keyboardWillShow(notification)
}
@objc private func keyboardHiddenNotificationReceived(_ notification: NSNotification) {
keyboardWillHide(notification)
}
}
extension DappsViewController: ActivityIndicating { /* mix-in */ }
extension DappsViewController: NavBarColorChanging {
var navTintColor: UIColor? { return nil }
var navBarTintColor: UIColor? { return Theme.tintColor }
var navTitleColor: UIColor? { return Theme.lightTextColor }
var navShadowImage: UIImage? { return UIImage() }
}
| gpl-3.0 | b30764ad2f81eac81b1dab736e916dc8 | 37.189239 | 202 | 0.684318 | 5.364608 | false | false | false | false |
lerigos/music-service | iOS_9/Pods/SwiftyVK/Source/API/Groups.swift | 2 | 7517 | extension _VKAPI {
///Methods for working with groups. More - https://vk.com/dev/groups
public struct Groups {
///Returns information specifying whether a user is a member of a community. More - https://vk.com/dev/users.get
public static func isMember(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.isMember", parameters: parameters)
}
///Returns information about communities by their IDs. More - https://vk.com/dev/groups.isMember
public static func getById(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getById", parameters: parameters)
}
///Returns a list of the communities to which a user belongs. More - https://vk.com/dev/groups.get
public static func get(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.get", parameters: parameters)
}
///Returns a list of community members. More - https://vk.com/dev/groups.getMembers
public static func getMembers(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getMembers", parameters: parameters)
}
///With this method you can join the group or public page, and also confirm your participation in an event. More - https://vk.com/dev/groups.join
public static func join(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.join", parameters: parameters)
}
///With this method you can leave a group, public page, or event. More - https://vk.com/dev/groups.leave
public static func leave(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.leave", parameters: parameters)
}
///Searches for communities by substring. More - https://vk.com/dev/groups.search
public static func search(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.search", parameters: parameters)
}
///Returns a list of invitations to join communities and events. More - https://vk.com/dev/groups.getInvites
public static func getInvites(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getInvites", parameters: parameters)
}
///Returns invited user. More - https://vk.com/dev/groups.getInvitedUsers
public static func getInvitedUsers(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getInvitedUsers", parameters: parameters)
}
///Adds a user to a community blacklist. More - https://vk.com/dev/groups.banUser
public static func banUser(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.banUser", parameters: parameters)
}
///Deletes a user from a community blacklist. More - https://vk.com/dev/groups.unbanUser
public static func unbanUser(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.unbanUser", parameters: parameters)
}
///Returns a list of users on a community blacklist. More - https://vk.com/dev/groups.getBanned
public static func getBanned(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getBanned", parameters: parameters)
}
///Create new community. More - https://vk.com/dev/groups.create
public static func create(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.create", parameters: parameters)
}
///Edit community info. More - https://vk.com/dev/groups.edit
public static func edit(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.edit", parameters: parameters)
}
///Edit community places. More - https://vk.com/dev/groups.editPlace
public static func editPlace(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.editPlace", parameters: parameters)
}
///Returns data necessary to display the data editing community. More - https://vk.com/dev/groups.getSettings
public static func getSettings(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getSettings", parameters: parameters)
}
///Returns a list requests for entry into the community. More - https://vk.com/dev/groups.getRequests
public static func getRequests(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getRequests", parameters: parameters)
}
///Allows you to assign/demote a manager in the community, or to change the level of its powers. More - https://vk.com/dev/groups.editManager
public static func editManager(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.editManager", parameters: parameters)
}
///Allows invite users to community. More - https://vk.com/dev/groups.invite
public static func invite(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.invite", parameters: parameters)
}
///Allows add links to community. More - https://vk.com/dev/groups.addLink
public static func addLink(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.addLink", parameters: parameters)
}
///Allows remove links to community. More - https://vk.com/dev/groups.deleteLink
public static func deleteLink(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.deleteLink", parameters: parameters)
}
///Allows edit links to community. More - https://vk.com/dev/groups.editLink
public static func editLink(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.editLink", parameters: parameters)
}
///Allows you to change the location of the reference list. More - https://vk.com/dev/groups.reorderLink
public static func reorderLink(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.reorderLink", parameters: parameters)
}
///Allows edit user to community. More - https://vk.com/dev/groups.removeUser
public static func removeUser(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.removeUser", parameters: parameters)
}
///Allows you to approve a request from the user to the community. More - https://vk.com/dev/groups.approveRequest
public static func approveRequest(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.approveRequest", parameters: parameters)
}
///Returns list of groups of selected category. More - https://vk.com/dev/groups.getCatalog
public static func getCatalog(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getCatalog", parameters: parameters)
}
///Returns list of categories of selected group. More - https://vk.com/dev/groups.getCatalogInfo
public static func getCatalogInfo(parameters: [VK.Arg : String] = [:]) -> Request {
return Request(method: "groups.getCatalogInfo", parameters: parameters)
}
}
}
| apache-2.0 | 9e07ff49e51833f26b13bf8ffea28493 | 37.352041 | 149 | 0.645869 | 4.315155 | false | false | false | false |
huonw/swift | test/SILOptimizer/devirt_inherited_conformance.swift | 3 | 5287 | // RUN: %target-swift-frontend -O %s -emit-sil | %FileCheck %s
// Make sure that we can dig all the way through the class hierarchy and
// protocol conformances.
// CHECK-LABEL: sil @$S28devirt_inherited_conformance6driveryyF : $@convention(thin) () -> () {
// CHECK: bb0
// CHECK: [[UNKNOWN2a:%.*]] = function_ref @unknown2a : $@convention(thin) () -> ()
// CHECK: apply [[UNKNOWN2a]]
// CHECK: apply [[UNKNOWN2a]]
// CHECK: [[UNKNOWN3a:%.*]] = function_ref @unknown3a : $@convention(thin) () -> ()
// CHECK: apply [[UNKNOWN3a]]
// CHECK: apply [[UNKNOWN3a]]
// CHECK: return
@_silgen_name("unknown1a")
func unknown1a() -> ()
@_silgen_name("unknown1b")
func unknown1b() -> ()
@_silgen_name("unknown2a")
func unknown2a() -> ()
@_silgen_name("unknown2b")
func unknown2b() -> ()
@_silgen_name("unknown3a")
func unknown3a() -> ()
@_silgen_name("unknown3b")
func unknown3b() -> ()
struct Int32 {}
protocol P {
// We do not specialize typealias's correctly now.
//typealias X
func doSomething(_ x : Int32)
// This exposes a SILGen bug. FIXME: Fix up this test in the future.
// class func doSomethingMeta()
}
class B : P {
// We do not specialize typealias's correctly now.
//typealias X = B
func doSomething(_ x : Int32) {
unknown1a()
}
// See comment in protocol P
//class func doSomethingMeta() {
// unknown1b()
//}
}
class B2 : B {
// When we have covariance in protocols, change this to B2.
// We do not specialize typealias correctly now.
//typealias X = B
override func doSomething(_ x : Int32) {
unknown2a()
}
// See comment in protocol P
//override class func doSomethingMeta() {
// unknown2b()
//}
}
class B3 : B {
// When we have covariance in protocols, change this to B3.
// We do not specialize typealias correctly now.
//typealias X = B
override func doSomething(_ x : Int32) {
unknown3a()
}
// See comment in protocol P
//override class func doSomethingMeta() {
// unknown3b()
//}
}
func WhatShouldIDo<T : P>(_ t : T, _ x : Int32) {
t.doSomething(x)
}
func WhatShouldIDo2(_ p : P, _ x : Int32) {
p.doSomething(x)
}
public func driver() -> () {
let b2 = B2()
let b3 = B3()
let x = Int32()
WhatShouldIDo(b2, x)
WhatShouldIDo2(b2, x)
WhatShouldIDo(b3, x)
WhatShouldIDo2(b3, x)
}
// Test that inherited conformances work properly with
// standard operators like == and custom operators like ---
// Comparable is similar to Equatable, but uses a usual method
// instead of an operator.
public protocol Comparable {
func compare(_: Self, _: Self) -> Bool
}
// Define a custom operator to be used instead of ==
infix operator --- { associativity left precedence 140 }
// Simple is a protocol that simply defines an operator and
// a few methods with different number of arguments.
public protocol Simple {
func foo(_: Self) -> Bool
func boo(_: Self, _: Self) -> Bool
func ---(_: Self, _: Self) -> Bool
}
public class C: Equatable, Comparable, Simple {
public func compare(_ c1:C, _ c2:C) -> Bool {
return c1 == c2
}
public func foo(_ c:C) -> Bool {
return true
}
public func boo(_ c1:C, _ c2:C) -> Bool {
return false
}
}
// D inherits a bunch of conformances from C.
// We want to check that compiler can handle
// them properly and is able to devirtualize
// them.
public class D: C {
}
public func ==(lhs: C, rhs: C) -> Bool {
return true
}
public func ---(lhs: C, rhs: C) -> Bool {
return true
}
public func compareEquals<T:Equatable>(_ x: T, _ y:T) -> Bool {
return x == y
}
public func compareMinMinMin<T:Simple>(_ x: T, _ y:T) -> Bool {
return x --- y
}
public func compareComparable<T:Comparable>(_ x: T, _ y:T) -> Bool {
return x.compare(x, y)
}
// Check that a call of inherited Equatable.== can be devirtualized.
// CHECK-LABEL: sil @$S28devirt_inherited_conformance17testCompareEqualsSbyF : $@convention(thin) () -> Bool {
// CHECK: bb0
// CHECK-NEXT: integer_literal $Builtin.Int1, -1
// CHECK-NEXT: struct $Bool
// CHECK: return
// CHECK: }
public func testCompareEquals() -> Bool {
return compareEquals(D(), D())
}
// Check that a call of inherited Simple.== can be devirtualized.
// CHECK-LABEL: sil @$S28devirt_inherited_conformance014testCompareMinfF0SbyF : $@convention(thin) () -> Bool {
// CHECK: bb0
// CHECK-NEXT: integer_literal $Builtin.Int1, -1
// CHECK-NEXT: struct $Bool
// CHECK: return
public func testCompareMinMinMin() -> Bool {
return compareMinMinMin(D(), D())
}
// Check that a call of inherited Comparable.== can be devirtualized.
// CHECK-LABEL: sil @$S28devirt_inherited_conformance21testCompareComparableSbyF : $@convention(thin) () -> Bool {
// CHECK: bb0
// CHECK-NEXT: integer_literal $Builtin.Int1, -1
// CHECK-NEXT: struct $Bool
// CHECK: return
public func testCompareComparable() -> Bool {
return compareComparable(D(), D())
}
public func BooCall<T:Simple>(_ x:T, _ y:T) -> Bool {
return x.boo(y, y)
}
// Check that a call of inherited Simple.boo can be devirtualized.
// CHECK-LABEL: sil @$S28devirt_inherited_conformance11testBooCallSbyF : $@convention(thin) () -> Bool {
// CHECK: bb0
// CHECK-NEXT: integer_literal $Builtin.Int1, 0
// CHECK-NEXT: struct $Bool
// CHECK: return
public func testBooCall() -> Bool {
return BooCall(D(), D())
}
| apache-2.0 | a70466a3d99b663d530af3415efa4c8f | 24.418269 | 114 | 0.656327 | 3.325157 | false | false | false | false |
lukevanin/OCRAI | GoogleNaturalLanguageAPI/JSON.swift | 1 | 4742 | //
// JSON.swift
// CardScanner
//
// Created by Luke Van In on 2017/02/18.
// Copyright © 2017 Luke Van In. All rights reserved.
//
import Foundation
extension GoogleNaturalLanguageAPI.EncodingType {
var json: String {
switch self {
case .none:
return "NONE"
case .utf8:
return "UTF8"
case .utf16:
return "UTF16"
case .utf32:
return "UTF32"
}
}
}
extension GoogleNaturalLanguageAPI.DocumentType {
var json: String {
switch self {
case .unspecified:
return "TYPE_UNSPECIFIED"
case .plaintext:
return "PLAIN_TEXT"
case .html:
return "HTML"
}
}
}
extension GoogleNaturalLanguageAPI.Document {
var json: [String: Any] {
var output = [String: Any]()
output["type"] = type.json
output["content"] = content
if let language = language {
output["language"] = language
}
return output
}
}
extension GoogleNaturalLanguageAPI.AnalyzeEntitiesRequest {
var json: [String: Any] {
return [
"document": document.json,
"encodingType": encodingType.json
]
}
}
extension GoogleNaturalLanguageAPI.EntityMentionType {
init(json: Any) throws {
guard let value = json as? String else {
throw GoogleNaturalLanguageAPI.APIError.parse
}
switch value {
case "TYPE_UNKNOWN":
self = .unknown
case "PROPER":
self = .proper
case "COMMON":
self = .common
default:
throw GoogleNaturalLanguageAPI.APIError.parse
}
}
}
extension GoogleNaturalLanguageAPI.TextSpan {
init(json: Any) throws {
guard
let container = json as? [String: Any],
let content = container["content"] as? String,
let beginOffset = container["beginOffset"] as? Int
else {
throw GoogleNaturalLanguageAPI.APIError.parse
}
self.content = content
self.beginOffset = beginOffset
}
}
extension GoogleNaturalLanguageAPI.EntityMention {
init(json: Any) throws {
guard
let container = json as? [String: Any],
let type = container["type"] as? String,
let text = container["text"]
else {
throw GoogleNaturalLanguageAPI.APIError.parse
}
self.type = try GoogleNaturalLanguageAPI.EntityMentionType(json: type)
self.text = try GoogleNaturalLanguageAPI.TextSpan(json: text)
}
}
extension GoogleNaturalLanguageAPI.EntityType {
init(json: Any) throws {
guard let value = json as? String else {
throw GoogleNaturalLanguageAPI.APIError.parse
}
switch value {
case "UNKNOWN":
self = .unknown
case "PERSON":
self = .person
case "LOCATION":
self = .location
case "ORGANIZATION":
self = .organization
case "EVENT":
self = .event
case "WORK_OF_ART":
self = .art
case "CONSUMER_GOOD":
self = .consumergoods
case "OTHER":
self = .other
default:
throw GoogleNaturalLanguageAPI.APIError.parse
}
}
}
extension GoogleNaturalLanguageAPI.Entity {
init(json: Any) throws {
guard
let container = json as? [String: Any],
let name = container["name"] as? String,
let type = container["type"] as? String,
let metadata = container["metadata"] as? [String: String],
let salience = container["salience"] as? Double,
let mentions = container["mentions"] as? [Any]
else {
throw GoogleNaturalLanguageAPI.APIError.parse
}
self.name = name
self.type = try GoogleNaturalLanguageAPI.EntityType(json: type)
self.metadata = metadata
self.salience = salience
self.mentions = try mentions.map { try GoogleNaturalLanguageAPI.EntityMention(json: $0) }
}
}
extension GoogleNaturalLanguageAPI.AnalyzeEntitiesResponse {
init(json: Any) throws {
guard
let container = json as? [String: Any],
let entities = container["entities"] as? [Any],
let language = container["language"] as? String
else {
throw GoogleNaturalLanguageAPI.APIError.parse
}
self.entities = try entities.map { try GoogleNaturalLanguageAPI.Entity(json: $0) }
self.language = language
}
}
| mit | 31f552c85ae256a2125f49b07fca72ee | 26.404624 | 97 | 0.562329 | 4.634409 | false | false | false | false |
tkausch/swiftalgorithms | SwiftAPI/Tuples.playground/Contents.swift | 1 | 4161 |
//: # Generating all Possibilities
//: Our goal in this section is to study methods for running through all of the possibilities in some combinatorial universe, because
//: we often face problems in which an exhaustive examination of all cases is necessary or desirable. For example we want
//: to look at all permutations of a given set.
//:
//: Some authors call this task of *enumerating* or *listing* all of the possibilities. In fact we do not really want to go though all
//: permutations but we want to have them present momentarily in some data structure, so that a program can
//: examine each permution one at a time.
//:
//: So we will speak of *generating* all of the combinatorial objects that we need, and *visiting* each object in turn. Just as
//: we have algorithms for tree traversal, we now look for algorithms that systematically traverse a combinatorial space
//: space of possibilities.
//: ## Generating all n-tuples
//: Let's start small, by considering how to run through all `2^n` strings that consist of n binary digits. Equivalently we want
//: to visit all n-tuples `(a1,...,an)` where each `aj` is either 0 or 1. This task is also, in essence, equivalent to
//: examining all subsets of a given set `{x1,...,xn}`, because we can say that `xj` is in the subset if and only if
//: `aj=1`.
//:
//: Such a problem has a simple solution. All we need to do is start with the binary number `(0...0)2 = 0` and
//: repeatedly add 1 until we reach `(1...11)2 = 2^n-1`.
//:
//: In the first place we can see, that the binary-notation trick extendes to other kind of n-tuples. If we want, for example,
//: to generate all `(a1,...,an)` in which each aj is one of the dicimal digits '{0,1,2,3,4,5,6,7,8,9}', we can simply count
//: from `(0...00)10 = 0` to `(9...99)10 = 10^n-1` in the decimal number system.
public struct Tuple: CustomStringConvertible {
public let a: [Int]
public let radix: Int
public var n: Int {
a.count
}
init(n: Int, radix: Int) {
self.a = Array(repeating: 0, count: n)
self.radix = radix
}
init(a: [Int], radix: Int) {
self.a = a
self.radix = radix
}
public var description: String {
return "(" + a.map(String.init).joined(separator: ", ") + ")"
}
}
extension Tuple {
public struct TupleGenerator: Sequence, IteratorProtocol {
public typealias Element = Tuple
private var t: Tuple?
init(n: Int, radix: Int) {
self.t = Tuple(a: Array(repeating: 0, count: n), radix: radix)
}
public mutating func next() -> Tuple? {
guard let t = self.t else {
return nil
}
let result = t
self.t = t.addOne()
return result
}
}
public func generator() -> TupleGenerator {
return TupleGenerator(n: a.count, radix: self.radix)
}
private func addOne() -> Tuple? {
var piggy = 1
var result = Array(a.reversed())
for i in result.indices {
if piggy == 0 {
break
} else {
let t = piggy + result[i]
if t < radix {
result[i] = t
piggy = 0
} else {
result[i] = 0
piggy = 1
}
}
}
if piggy == 1 {
return nil
} else {
return Tuple(a: result.reversed(), radix: radix)
}
}
}
let t = Tuple(n: 4, radix: 3)
for t in t.generator() {
print(t)
}
//: The above algorithm is simple and straight forward, but we shouldn't forget that nested loops are even simpler, when `n` is fairly a
//: small constant. When `n = 4` and `radix = 3` the following is equivalent. These instructions are equal and can be easily expressed.
let m = 0...3
for a1 in m {
for a2 in m {
for a3 in m {
for a4 in m {
print(Tuple(a: [a1, a2, a3, a4], radix: 3))
}
}
}
}
| gpl-3.0 | 3544160e643fe65f9772f28263c94da9 | 32.02381 | 136 | 0.572699 | 3.974212 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/SwiftUI/Components/CapsuleView.swift | 1 | 4276 | //
// Xcore
// Copyright © 2021 Xcore
// MIT license, see LICENSE file for details
//
import SwiftUI
/// A stylized view, with an optional label, that is visually presented in a
/// capsule shape.
public struct CapsuleView<Label>: View where Label: View {
@Environment(\.theme) private var theme
private let image: SystemAssetIdentifier?
private let title: Text
private let label: () -> Label
public var body: some View {
HStack(spacing: .s4) {
if let image = image {
Image(system: image)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(28)
}
VStack {
title
.font(.app(.headline, weight: .semibold))
if Label.self != Never.self {
label()
.font(.app(.subheadline))
.foregroundColor(theme.textSecondaryColor)
}
}
.padding(hasImage ? .trailing : .horizontal)
}
.padding(.horizontal)
.frame(minHeight: 56)
.background(Color(light: .systemBackground, dark: .secondarySystemBackground))
.clipShape(Capsule())
.floatingShadow()
.accessibilityElement(children: .combine)
}
private var hasImage: Bool {
image != nil
}
}
// MARK: - Inits
extension CapsuleView {
public init(
_ title: Text,
systemImage: SystemAssetIdentifier? = nil,
@ViewBuilder label: @escaping () -> Label
) {
self.image = systemImage
self.title = title
self.label = label
}
public init<S>(
_ title: S,
systemImage: SystemAssetIdentifier? = nil,
@ViewBuilder label: @escaping () -> Label
) where S: StringProtocol {
self.init(Text(title), systemImage: systemImage, label: label)
}
}
extension CapsuleView where Label == Text? {
public init(
_ title: Text,
subtitle: Text?,
systemImage: SystemAssetIdentifier? = nil
) {
self.init(title, systemImage: systemImage) {
subtitle.map { $0 }
}
}
public init<S1, S2>(
_ title: S1,
subtitle: S2?,
systemImage: SystemAssetIdentifier? = nil
) where S1: StringProtocol, S2: StringProtocol {
self.init(title, systemImage: systemImage) {
subtitle.map { Text($0) }
}
}
}
extension CapsuleView where Label == Never {
public init(
_ title: Text,
systemImage: SystemAssetIdentifier? = nil
) {
self.init(title, systemImage: systemImage) {
fatalError()
}
}
public init<S>(
_ title: S,
systemImage: SystemAssetIdentifier? = nil
) where S: StringProtocol {
self.init(title, systemImage: systemImage) {
fatalError()
}
}
}
#if DEBUG
// MARK: - Preview Provider
@available(iOS 15.0, *)
struct CapsuleView_Previews: PreviewProvider {
static var previews: some View {
Samples.capsuleViewPreviews
.colorScheme(.light)
}
}
extension Samples {
@available(iOS 15.0, *)
public static var capsuleViewPreviews: some View {
LazyView {
ZStack {
Color(.systemBackground)
.ignoresSafeArea()
VStack(spacing: .s6) {
CapsuleView("Apple Pencil") {
HStack {
Text("100%")
Image(system: .battery100Bolt)
.renderingMode(.original)
}
}
CapsuleView("Do Not Disturb", subtitle: "On", systemImage: .moonFill)
.foregroundColor(.indigo)
.colorScheme(.dark)
CapsuleView("No Internet Connection", systemImage: .boltSlashFill)
.foregroundColor(.orange)
CapsuleView("Mail pasted from Photos")
CapsuleView("Dismiss")
CapsuleView("9:41 AM", systemImage: .bellFill)
}
}
}
}
}
#endif
| mit | e3dbfb66c9b66e9ba6767dd25167a171 | 25.552795 | 89 | 0.521404 | 4.718543 | false | false | false | false |
JaSpa/swift | test/SILGen/partial_apply_generic.swift | 4 | 2495 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
protocol Foo {
static func staticFunc()
func instanceFunc()
}
// CHECK-LABEL: sil hidden @_T021partial_apply_generic14getStaticFunc1{{[_0-9a-zA-Z]*}}F
func getStaticFunc1<T: Foo>(t: T.Type) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK-NEXT: apply [[REF]]<T>(%0)
return t.staticFunc
// CHECK-NEXT: return
}
// CHECK-LABEL: sil shared [thunk] @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.staticFunc!1
// CHECK-NEXT: partial_apply [[REF]]<Self>(%0)
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_T021partial_apply_generic14getStaticFunc2{{[_0-9a-zA-Z]*}}F
func getStaticFunc2<T: Foo>(t: T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP10staticFunc{{[_0-9a-zA-Z]*}}FZ
// CHECK: apply [[REF]]<T>
return T.staticFunc
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc1{{[_0-9a-zA-Z]*}}F
func getInstanceFunc1<T: Foo>(t: T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization]
// CHECK-NEXT: apply [[REF]]<T>
return t.instanceFunc
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: return
}
// CHECK-LABEL: sil shared [thunk] @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK: [[REF:%.*]] = witness_method $Self, #Foo.instanceFunc!1
// CHECK-NEXT: partial_apply [[REF]]<Self>(%0)
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc2{{[_0-9a-zA-Z]*}}F
func getInstanceFunc2<T: Foo>(t: T) -> (T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: partial_apply [[REF]]<T>(
return T.instanceFunc
// CHECK-NEXT: destroy_addr %0 : $*
// CHECK-NEXT: return
}
// CHECK-LABEL: sil hidden @_T021partial_apply_generic16getInstanceFunc3{{[_0-9a-zA-Z]*}}F
func getInstanceFunc3<T: Foo>(t: T.Type) -> (T) -> () -> () {
// CHECK: [[REF:%.*]] = function_ref @_T021partial_apply_generic3FooP12instanceFunc{{[_0-9a-zA-Z]*}}F
// CHECK-NEXT: partial_apply [[REF]]<T>(
return t.instanceFunc
// CHECK-NEXT: return
}
| apache-2.0 | 8a882c8993d8700f906f86f7ded857af | 38.603175 | 101 | 0.656914 | 2.935294 | false | false | false | false |
folse/Member_iOS | member/Signup.swift | 1 | 4997 | //
// Signup.swift
// member
//
// Created by Jennifer on 7/1/15.
// Copyright (c) 2015 Folse. All rights reserved.
//
import UIKit
class Signup: UITableViewController {
@IBOutlet weak var phoneTextField: UITextField!
@IBOutlet weak var realNameTextField: UITextField!
@IBOutlet weak var quantityTextField: UITextField!
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
phoneTextField.text = ""
realNameTextField.text = ""
quantityTextField.text = ""
}
override func viewDidLoad() {
super.viewDidLoad()
phoneTextField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func DoneButtonAction(sender: UIBarButtonItem) {
if phoneTextField.text.length != 0 && realNameTextField.text.length != 0 {
self.view.endEditing(true)
if quantityTextField.text.length == 0 {
registerCustomer(phoneTextField.text, realName: realNameTextField.text, quantity:"0")
}else{
registerCustomer(phoneTextField.text, realName: realNameTextField.text, quantity:quantityTextField.text)
}
}
}
func registerCustomer(username:String,realName:String,quantity:String) {
var indicator = WIndicator.showIndicatorAddedTo(self.view, animation: true)
let manager = AFHTTPRequestOperationManager()
manager.responseSerializer.acceptableContentTypes = NSSet().setByAddingObject("text/html")
let url = API_ROOT + "membership_new"
println(url)
let shopId : String = NSUserDefaults.standardUserDefaults().objectForKey("shopId") as! String
let params:NSDictionary = ["customer_username":username,
"real_name":realName,
"shop_id":shopId,
"phone":username,
"email":"",
"quantity":quantity]
println(params)
manager.GET(url,
parameters: params as [NSObject : AnyObject],
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println(responseObject.description)
WIndicator.removeIndicatorFrom(self.view, animation: true)
let responseDict = responseObject as! Dictionary<String,AnyObject>
let responseCode = responseDict["resp"] as! String
if responseCode == "0000" {
var indicator = WIndicator.showSuccessInView(self.view, text:" ", timeOut:1)
var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "nextPage", userInfo: nil, repeats: false)
}else {
let message = responseDict["msg"] as! String
let alert = UIAlertView()
alert.title = "Denna operation kan inte slutföras"
alert.message = message
alert.addButtonWithTitle("OK")
alert.show()
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
WIndicator.removeIndicatorFrom(self.view, animation: true)
let alert = UIAlertView()
alert.title = "Denna operation kan inte slutföras"
alert.message = "Försök igen eller kontakta vår kundtjänst. För bättre och snabbare service, rekommenderar vi att du skickar oss en skärmdump." + error.localizedDescription + "\(error.code)"
alert.addButtonWithTitle("OK")
alert.show()
})
}
func nextPage() {
self.performSegueWithIdentifier("trade", sender: self)
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "trade"{
var segue = segue.destinationViewController as! Trade
segue.realName = realNameTextField.text
segue.customerUsername = phoneTextField.text
if quantityTextField.text.length > 0 {
segue.vaildQuantity = quantityTextField.text
}else{
segue.vaildQuantity = "0"
}
segue.punchedQuantity = "0"
}
}
}
| mit | 45244812b191d8b145702b596293f6bb | 33.638889 | 206 | 0.55413 | 5.542222 | false | false | false | false |
tellowkrinkle/Sword | Sources/Sword/Types/GuildVoice.swift | 1 | 2222 | //
// GuildVoice.swift
// Sword
//
// Created by Alejandro Alonso
//
/// Representation of a guild voice channel
public struct GuildVoice: GuildChannel {
// MARK: Properties
/// Parent Class
public internal(set) weak var sword: Sword?
/// Bitrate (in bits) for channel
public let bitrate: Int?
/// Guild object for this channel
public internal(set) weak var guild: Guild?
/// ID of the channel
public let id: ChannelID
/// Name of channel
public let name: String?
/// Collection of Overwrites mapped by `OverwriteID`
public internal(set) var permissionOverwrites = [OverwriteID : Overwrite]()
/// Position of channel
public let position: Int?
/// Indicates what type of channel this is (.guildVoice)
public let type: ChannelType
/// (Voice) User limit for voice channel
public let userLimit: Int?
// MARK: Initializer
/**
Creates a GuildVoice structure
- parameter sword: Parent class
- parameter json: JSON represented as a dictionary
*/
init(_ sword: Sword, _ json: [String: Any]) {
self.sword = sword
self.bitrate = json["bitrate"] as? Int
self.id = ChannelID(json["id"] as! String)!
self.guild = sword.guilds[Snowflake(json["guild_id"] as! String)!]
let name = json["name"] as? String
self.name = name
if let overwrites = json["permission_overwrites"] as? [[String: Any]] {
for overwrite in overwrites {
let overwrite = Overwrite(overwrite)
self.permissionOverwrites[overwrite.id] = overwrite
}
}
self.position = json["position"] as? Int
self.type = ChannelType(rawValue: json["type"] as! Int)!
self.userLimit = json["user_limit"] as? Int
}
// MARK: Functions
/**
Moves a member in this voice channel to another voice channel (if they are in it)
- parameter userId: User to move
*/
public func moveMember(_ userId: UserID, then completion: @escaping (RequestError?) -> () = {_ in}) {
guard let guild = self.guild else { return }
self.sword?.request(.modifyGuildMember(guild.id, userId), body: ["channel_id": self.id.description]) { data, error in
completion(error)
}
}
}
| mit | 3d8258165d043e60074c3923ed8b85f4 | 25.141176 | 121 | 0.644464 | 4.145522 | false | false | false | false |
wikimedia/apps-ios-wikipedia | Wikipedia/Code/TalkPagesController.swift | 1 | 15156 |
import Foundation
enum TalkPageError: Error {
case createTaskURLFailure
case fetchLocalTalkPageFailure
case updateLocalTalkPageFailure
case createLocalTalkPageFailure
case fetchNetworkTalkPageFailure
case fetchRevisionIDFailure
case talkPageDatabaseKeyCreationFailure
case revisionUrlCreationFailure
case talkPageTitleCreationFailure
case createUrlTitleStringFailure
case freshFetchTaskGroupFailure
case topicMissingTalkPageRelationship
case unableToDetermineAbsoluteURL
var localizedDescription: String {
return CommonStrings.genericErrorDescription
}
}
enum TalkPageAppendSuccessResult {
case missingRevisionIDInResult
case refreshFetchFailed
case success
}
class TalkPageController {
let fetcher: TalkPageFetcher
let articleRevisionFetcher: WMFArticleRevisionFetcher
let moc: NSManagedObjectContext
let title: String
let siteURL: URL
let type: TalkPageType
var displayTitle: String {
return type.titleWithoutNamespacePrefix(title: title)
}
required init(fetcher: TalkPageFetcher = TalkPageFetcher(), articleRevisionFetcher: WMFArticleRevisionFetcher = WMFArticleRevisionFetcher(), moc: NSManagedObjectContext, title: String, siteURL: URL, type: TalkPageType) {
self.fetcher = fetcher
self.articleRevisionFetcher = articleRevisionFetcher
self.moc = moc
self.title = title
self.siteURL = siteURL
self.type = type
assert(title.contains(":"), "Title must already be prefixed with namespace.")
}
struct FetchResult {
let objectID: NSManagedObjectID
let isInitialLocalResult: Bool
}
func fetchTalkPage(completion: ((Result<FetchResult, Error>) -> Void)? = nil) {
guard let urlTitle = type.urlTitle(for: title),
let taskURL = fetcher.getURL(for: urlTitle, siteURL: siteURL) else {
completion?(.failure(TalkPageError.createTaskURLFailure))
return
}
moc.perform {
do {
guard let localTalkPage = try self.moc.talkPage(for: taskURL) else {
self.createTalkPage(with: urlTitle, taskURL: taskURL, in: self.moc, completion: { (result) in
switch result {
case .success(let response):
let fetchResult = FetchResult(objectID: response, isInitialLocalResult: false)
completion?(.success(fetchResult))
case .failure(let error):
completion?(.failure(error))
}
})
return
}
//fixes bug where revisionID fetch fails due to missing talk page
if localTalkPage.isMissing {
let fetchResult = FetchResult(objectID: localTalkPage.objectID, isInitialLocalResult: false)
completion?(.success(fetchResult))
return
}
//return initial local result early to display data while API is being called
let fetchResult = FetchResult(objectID: localTalkPage.objectID, isInitialLocalResult: true)
completion?(.success(fetchResult))
let localObjectID = localTalkPage.objectID
let localRevisionID = localTalkPage.revisionId?.intValue
self.fetchLatestRevisionID(endingWithRevision: localRevisionID, urlTitle: urlTitle) { (result) in
switch result {
case .success(let lastRevisionID):
//if latest revision ID is the same return local talk page. else forward revision ID onto talk page fetcher
if localRevisionID == lastRevisionID {
let fetchResult = FetchResult(objectID: localObjectID, isInitialLocalResult: false)
completion?(.success(fetchResult))
} else {
self.fetchAndUpdateLocalTalkPage(with: localObjectID, revisionID: lastRevisionID, completion: { (result) in
switch result {
case .success(let response):
let fetchResult = FetchResult(objectID: response, isInitialLocalResult: false)
completion?(.success(fetchResult))
case .failure(let error):
completion?(.failure(error))
}
})
}
case .failure(let error):
completion?(.failure(error))
}
}
} catch {
completion?(.failure(TalkPageError.fetchLocalTalkPageFailure))
return
}
}
}
func createTalkPage(with urlTitle: String, taskURL: URL, in moc: NSManagedObjectContext, completion: ((Result<NSManagedObjectID, Error>) -> Void)? = nil) {
//If no local talk page to reference, fetch latest revision ID & latest talk page in grouped calls.
//Update network talk page with latest revision & save to db
let taskGroup = WMFTaskGroup()
taskGroup.enter()
var revisionID: Int?
fetchLatestRevisionID(endingWithRevision: nil, urlTitle: urlTitle) { (result) in
switch result {
case .success(let resultRevisionID):
revisionID = resultRevisionID
case .failure:
break
}
taskGroup.leave()
}
taskGroup.enter()
var networkTalkPage: NetworkTalkPage?
var talkPageDoesNotExist: Bool = false
fetchTalkPage(revisionID: nil) { (result) in
switch result {
case .success(let resultNetworkTalkPage):
networkTalkPage = resultNetworkTalkPage
case .failure(let error):
if let talkPageFetcherError = error as? TalkPageFetcherError,
talkPageFetcherError == .talkPageDoesNotExist {
talkPageDoesNotExist = true
}
}
taskGroup.leave()
}
taskGroup.waitInBackground {
moc.perform {
if talkPageDoesNotExist {
if let newLocalTalkPage = moc.createMissingTalkPage(with: taskURL, displayTitle: self.displayTitle) {
completion?(.success(newLocalTalkPage.objectID))
} else {
completion?(.failure(TalkPageError.createLocalTalkPageFailure))
}
} else {
guard let revisionID = revisionID,
let networkTalkPage = networkTalkPage else {
completion?(.failure(TalkPageError.freshFetchTaskGroupFailure))
return
}
networkTalkPage.revisionId = revisionID
if let newLocalTalkPage = moc.createTalkPage(with: networkTalkPage) {
completion?(.success(newLocalTalkPage.objectID))
} else {
completion?(.failure(TalkPageError.createLocalTalkPageFailure))
}
}
}
}
}
private var signatureIfAutoSignEnabled: String {
return UserDefaults.wmf.autoSignTalkPageDiscussions ? " ~~~~" : ""
}
func addTopic(toTalkPageWith talkPageObjectID: NSManagedObjectID, title: String, siteURL: URL, subject: String, body: String, completion: @escaping (Result<TalkPageAppendSuccessResult, Error>) -> Void) {
guard let title = type.urlTitle(for: title) else {
completion(.failure(TalkPageError.createUrlTitleStringFailure))
return
}
let wrappedBody = "<p>\n\n" + body + "\(signatureIfAutoSignEnabled)</p>"
fetcher.addTopic(to: title, siteURL: siteURL, subject: subject, body: wrappedBody) { (result) in
switch result {
case .success(let result):
guard let newRevisionID = result["newrevid"] as? Int else {
completion(.success(.missingRevisionIDInResult))
return
}
self.fetchAndUpdateLocalTalkPage(with: talkPageObjectID, revisionID: newRevisionID, completion: { (result) in
self.moc.perform {
// Mark new topic as read since the user created it
let talkPage = self.moc.talkPage(with: talkPageObjectID)
let probablyNewTopic = talkPage?.topics?.sortedArray(using: [NSSortDescriptor(key: "sort", ascending: true)]).last as? TalkPageTopic
probablyNewTopic?.isRead = true
switch result {
case .success:
completion(.success(.success))
case .failure:
completion(.success(.refreshFetchFailed))
}
}
})
case .failure(let error):
completion(.failure(error))
}
}
}
func addReply(to topic: TalkPageTopic, title: String, siteURL: URL, body: String, completion: @escaping (Result<TalkPageAppendSuccessResult, Error>) -> Void) {
guard let title = type.urlTitle(for: title) else {
completion(.failure(TalkPageError.createUrlTitleStringFailure))
return
}
let wrappedBody = "<p>\n\n" + body + "\(signatureIfAutoSignEnabled)</p>"
let talkPageTopicID = topic.objectID
guard let talkPageObjectID = topic.talkPage?.objectID else {
completion(.failure(TalkPageError.topicMissingTalkPageRelationship))
return
}
fetcher.addReply(to: topic, title: title, siteURL: siteURL, body: wrappedBody) { (result) in
switch result {
case .success(let result):
guard let newRevisionID = result["newrevid"] as? Int else {
completion(.success(.missingRevisionIDInResult))
return
}
self.fetchAndUpdateLocalTalkPage(with: talkPageObjectID, revisionID: newRevisionID, completion: { (result) in
self.moc.perform {
// Mark updated topic as read since the user added to it
let topic = self.moc.talkPageTopic(with: talkPageTopicID)
topic?.isRead = true
switch result {
case .success:
completion(.success(.success))
case .failure:
completion(.success(.refreshFetchFailed))
}
}
})
case .failure(let error):
completion(.failure(error))
}
}
}
}
//MARK: Private
private extension TalkPageController {
func fetchLatestRevisionID(endingWithRevision revisionID: Int?, urlTitle: String, completion: @escaping (Result<Int, Error>) -> Void) {
guard let host = siteURL.host,
let revisionURL = Configuration.current.mediaWikiAPIURForHost(host, with: nil).url?.wmf_URL(withTitle: urlTitle) else {
completion(.failure(TalkPageError.revisionUrlCreationFailure))
return
}
let errorHandler: (Error) -> Void = { error in
completion(.failure(TalkPageError.fetchRevisionIDFailure))
}
let successIDHandler: (Any) -> Void = { object in
let queryResults = (object as? [WMFRevisionQueryResults])?.first ?? (object as? WMFRevisionQueryResults)
guard let lastRevisionId = queryResults?.revisions.first?.revisionId.intValue else {
completion(.failure(TalkPageError.fetchRevisionIDFailure))
return
}
completion(.success(lastRevisionId))
}
let revisionIDNumber: NSNumber? = revisionID != nil ? NSNumber(value: revisionID!) : nil
let revisionFetcherTask = articleRevisionFetcher.fetchLatestRevisions(forArticleURL: revisionURL, resultLimit: 1, endingWithRevision: revisionIDNumber, failure: errorHandler, success: successIDHandler)
//todo: task tracking
revisionFetcherTask?.resume()
}
func fetchTalkPage(revisionID: Int?, completion: @escaping ((Result<NetworkTalkPage, Error>) -> Void)) {
guard let urlTitle = type.urlTitle(for: title) else {
completion(.failure(TalkPageError.talkPageTitleCreationFailure))
return
}
fetcher.fetchTalkPage(urlTitle: urlTitle, displayTitle: displayTitle, siteURL: siteURL, revisionID: revisionID, completion: completion)
}
func fetchAndUpdateLocalTalkPage(with moid: NSManagedObjectID, revisionID: Int, completion: ((Result<NSManagedObjectID, Error>) -> Void)? = nil) {
fetchTalkPage(revisionID: revisionID) { (result) in
self.moc.perform {
do {
guard let localTalkPage = try self.moc.existingObject(with: moid) as? TalkPage else {
completion?(.failure(TalkPageError.fetchLocalTalkPageFailure))
return
}
switch result {
case .success(let networkTalkPage):
assert(networkTalkPage.revisionId != nil, "Expecting network talk page to have a revision ID here so it can pass it into the local talk page.")
if let updatedLocalTalkPageID = self.moc.updateTalkPage(localTalkPage, with: networkTalkPage)?.objectID {
completion?(.success(updatedLocalTalkPageID))
} else {
completion?(.failure(TalkPageError.updateLocalTalkPageFailure))
}
case .failure(let error):
completion?(.failure(error))
}
} catch {
completion?(.failure(TalkPageError.fetchLocalTalkPageFailure))
}
}
}
}
}
extension TalkPage {
var isMissing: Bool {
return revisionId == nil
}
func userDidAccess() {
dateAccessed = Date()
}
}
| mit | b09b9400fc97213e993f83e014be9cd8 | 41.692958 | 224 | 0.555094 | 5.791364 | false | false | false | false |
cwaffles/Soulcast | Soulcast/ImproveButton.swift | 1 | 1753 | //
// ImproveButton.swift
// Soulcast
//
// Created by June Kim on 2016-11-12.
// Copyright © 2016 Soulcast-team. All rights reserved.
//
import Foundation
import UIKit
class ImproveButton: UIButton {
let buttonSize:CGFloat = 50
let margin:CGFloat = 25
override init(frame: CGRect) {
assert(frame == CGRect.zero)
super.init(frame: CGRect(
x: screenWidth - buttonSize - margin,
y: screenHeight - buttonSize - margin,
width: buttonSize,
height: buttonSize))
backgroundColor = offBlue
setTitleColor(UIColor.black, for: UIControlState())
let italicFont = UIFont(name: "Baskerville-BoldItalic", size: 15)!
let attributedTitle = NSAttributedString(string: "i", attributes: (NSDictionary(object: italicFont, forKey: NSFontAttributeName as NSCopying) as! [String : AnyObject]))
setAttributedTitle(attributedTitle, for: UIControlState())
clipsToBounds = false
layer.cornerRadius = buttonSize/2
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
alpha = 0
UIView.animate(withDuration: 1, animations: {
self.alpha = 1
})
let shadowView = UIView(frame: bounds)
let circlePath = UIBezierPath(
roundedRect: frame,
cornerRadius: layer.cornerRadius)
shadowView.layer.shadowColor = UIColor.black.withAlphaComponent(0.4).cgColor
shadowView.layer.shadowPath = circlePath.cgPath
shadowView.layer.shadowOffset = CGSize(width: 2, height: 2)
shadowView.layer.shadowOpacity = 1
shadowView.layer.shadowRadius = 6
layer.superlayer?.insertSublayer(shadowView.layer, below: layer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 425d888e7ba1f9a9f6f1550817e80e2b | 28.694915 | 172 | 0.698059 | 4.469388 | false | false | false | false |
hulu001/AMScrollingNavbar | Source/ScrollingNavbar+Sizes.swift | 2 | 1216 | import Foundation
/**
Implements the main functions providing constants values and computed ones
*/
extension ScrollingNavigationController {
// MARK: - View sizing
func fullNavbarHeight() -> CGFloat {
return navbarHeight() + statusBar()
}
func navbarHeight() -> CGFloat {
let isPortrait = UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation)
if UIDevice().userInterfaceIdiom == .Pad || UIScreen.mainScreen().scale == 3 {
return portraitNavbar()
} else {
return (isPortrait ? portraitNavbar() : landscapeNavbar())
}
}
func portraitNavbar() -> CGFloat {
guard let topViewController = self.topViewController else {
return 44
}
return 44 + ((topViewController.navigationItem.prompt != nil) ? 30 : 0)
}
func landscapeNavbar() -> CGFloat {
guard let topViewController = self.topViewController else {
return 32
}
return 32 + ((topViewController.navigationItem.prompt != nil) ? 22 : 0)
}
func statusBar() -> CGFloat {
return UIApplication.sharedApplication().statusBarHidden ? 0 : 20
}
}
| mit | d0462ce44f3bfcbd8e2f5129e4700b0b | 29.4 | 113 | 0.634868 | 5.527273 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab2Search/views/SLV_SearchThemeContentsCell.swift | 1 | 5535 | //
// SLV_SearchThemeContentsCell.swift
// selluv-ios
//
// Created by 조백근 on 2017. 3. 12..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
/*
검색> 테마의 섹션이하의 상세 테마 셀
*/
class SLV_SearchThemeContentsCell: UICollectionViewCell {
@IBOutlet weak var theme1View: UIView!
@IBOutlet weak var theme2View: UIView!
@IBOutlet weak var theme3View: UIView!
@IBOutlet weak var moreView: UIView!
@IBOutlet weak var themeImage1View: UIImageView!
@IBOutlet weak var themeImage2View: UIImageView!
@IBOutlet weak var themeImage3View: UIImageView!
@IBOutlet weak var moreImageView: UIImageView!
@IBOutlet weak var brandEnglish1Label: UILabel!
@IBOutlet weak var brandEnglish2Label: UILabel!
@IBOutlet weak var brandEnglish3Label: UILabel!
@IBOutlet weak var brandKorean1Label: UILabel!
@IBOutlet weak var brandKorean2Label: UILabel!
@IBOutlet weak var brandKorean3Label: UILabel!
@IBOutlet weak var brandPrice1Label: UILabel!
@IBOutlet weak var brandPrice2Label: UILabel!
@IBOutlet weak var brandPrice3Label: UILabel!
@IBOutlet weak var theme1Button: UIButton!
@IBOutlet weak var theme2Button: UIButton!
@IBOutlet weak var theme3Button: UIButton!
@IBOutlet weak var moreBrandEnglishLabel: UILabel!
@IBOutlet weak var closeButton: UIButton!
@IBOutlet weak var moreButton: UIButton!
var theme: SLVTheme?
var products: [SLVDetailProduct] = []
var brands: [Brand] = []
var actionBlock: ((_ index: Int, _ product: SLVDetailProduct?, _ brand: Brand?) -> Void)?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
func imageDomain() -> String {
return dnImage
}
func reset() {
self.products.removeAll()
self.brands.removeAll()
self.theme = nil
self.actionBlock = nil
}
func setupFoldingData(theme: SLVTheme) {
self.reset()
self.theme = theme
let productIds = theme.targetContents
if let list = productIds {
if list.count > 0 {
for (i, v) in list.enumerated() {
ProductsModel.shared.product(productId: v, completion: { (success, item) in
if success == true {
self.products.append(item!)
}
if i + 1 == list.count {
self.setupBrands()
}
})
}
}
}
}
func setupBrands() {
for (i, v) in self.products.enumerated() {
let brandId = v.brand?.brandId
BrandTabModel.shared.brandDetail(brandId: brandId!, completion: { (success, brandItem) in
if success == true {
self.brands.append(brandItem!)
}
if i + 1 == self.products.count {
self.setupBrandContents()
}
})
}
}
func setupBrandContents() {
let views = [
[self.themeImage1View, self.brandEnglish1Label, self.brandKorean1Label, self.brandPrice1Label],
[self.themeImage2View, self.brandEnglish2Label, self.brandKorean2Label, self.brandPrice2Label],
[self.themeImage3View, self.brandEnglish3Label, self.brandKorean3Label, self.brandPrice3Label]
]
for (i, _) in (self.theme?.targetContents?.enumerated())! {
let list = views[i]
let p = self.products[i] as SLVDetailProduct
let b = self.brands[i] as Brand
let img = p.photos?.first
let e_nm = b.english
let k_nm = b.korean
let price = p.price?.original ?? 0
let comma = String.decimalAmountWithForm(value: price, pointCount: 0)
(list[1] as! UILabel).text = e_nm
(list[2] as! UILabel).text = k_nm
(list[3] as! UILabel).text = comma
if img != "" {
let domain = dnProduct
let from = URL(string: "\(domain)\(img)")
let dnModel = SLVDnImageModel.shared
DispatchQueue.global(qos: .default).async {
dnModel.setupImageView(view: list[0] as! UIImageView, from: from!)
}
}
}
}
func setupAction(block: @escaping ((_ index: Int, _ product: SLVDetailProduct?, _ brand: Brand?) -> Void)) {
self.actionBlock = block
}
@IBAction func touchTheme1Button(_ sender: Any) {
if self.actionBlock != nil {
self.actionBlock!(0, self.products[0], self.brands[0])
}
}
@IBAction func touchTheme2Button(_ sender: Any) {
if self.actionBlock != nil {
self.actionBlock!(1, self.products[1], self.brands[1])
}
}
@IBAction func touchTheme3Button(_ sender: Any) {
if self.actionBlock != nil {
self.actionBlock!(2, self.products[2], self.brands[2])
}
}
@IBAction func touchCloseButton(_ sender: Any) {
}
@IBAction func touchMoreButton(_ sender: Any) {
}
}
| mit | f4053b79f010689093dd2bfdea6417a0 | 30.768786 | 112 | 0.563137 | 4.348101 | false | false | false | false |
ello/ello-ios | Sources/Controllers/Stream/SimpleStreamViewController.swift | 1 | 2181 | ////
/// SimpleStreamController.swift
//
class SimpleStreamViewController: StreamableViewController {
override func trackerName() -> String? {
return endpoint.trackerName
}
var navigationBar: ElloNavigationBar!
let endpoint: ElloAPI
let streamKind: StreamKind
required init(endpoint: ElloAPI, title: String) {
self.endpoint = endpoint
self.streamKind = .simpleStream(endpoint: endpoint, title: title)
super.init(nibName: nil, bundle: nil)
self.title = title
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
setupNavigationBar()
setupNavigationItems(streamKind: streamKind)
streamViewController.streamKind = streamKind
streamViewController.showLoadingSpinner()
streamViewController.loadInitialPage()
}
override func viewForStream() -> UIView {
return view
}
override func showNavBars(animated: Bool) {
super.showNavBars(animated: animated)
positionNavBar(navigationBar, visible: true, animated: animated)
updateInsets()
}
override func hideNavBars(animated: Bool) {
super.hideNavBars(animated: animated)
positionNavBar(navigationBar, visible: false, animated: animated)
updateInsets()
}
private func updateInsets() {
updateInsets(navBar: navigationBar)
}
private func setupNavigationBar() {
navigationBar = ElloNavigationBar(
frame: CGRect(
x: 0,
y: 0,
width: view.frame.width,
height: ElloNavigationBar.Size.height
)
)
navigationBar.autoresizingMask = [.flexibleBottomMargin, .flexibleWidth]
view.addSubview(navigationBar)
}
private func setupNavigationItems(streamKind: StreamKind) {
navigationBar.leftItems = [.back]
if streamKind.hasGridViewToggle {
navigationBar.rightItems = [.gridList(isGrid: streamKind.isGridView)]
}
}
}
| mit | da643f9bb45dfdf2ad3e86a6d15a43a0 | 26.961538 | 81 | 0.641907 | 5.131765 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxSwift/RxSwift/Observables/Amb.swift | 4 | 4835 | //
// Amb.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Propagates the observable sequence that reacts first.
- seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html)
- returns: An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
public static func amb<S: Sequence>(_ sequence: S) -> Observable<E>
where S.Iterator.Element == Observable<E> {
return sequence.reduce(Observable<S.Iterator.Element.E>.never()) { a, o in
return a.amb(o.asObservable())
}
}
}
extension ObservableType {
/**
Propagates the observable sequence that reacts first.
- seealso: [amb operator on reactivex.io](http://reactivex.io/documentation/operators/amb.html)
- parameter right: Second observable sequence.
- returns: An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
public func amb<O2: ObservableType>
(_ right: O2)
-> Observable<E> where O2.E == E {
return Amb(left: self.asObservable(), right: right.asObservable())
}
}
fileprivate enum AmbState {
case neither
case left
case right
}
final private class AmbObserver<O: ObserverType>: ObserverType {
typealias Element = O.E
typealias Parent = AmbSink<O>
typealias This = AmbObserver<O>
typealias Sink = (This, Event<Element>) -> Void
fileprivate let _parent: Parent
fileprivate var _sink: Sink
fileprivate var _cancel: Disposable
init(parent: Parent, cancel: Disposable, sink: @escaping Sink) {
#if TRACE_RESOURCES
_ = Resources.incrementTotal()
#endif
self._parent = parent
self._sink = sink
self._cancel = cancel
}
func on(_ event: Event<Element>) {
self._sink(self, event)
if event.isStopEvent {
self._cancel.dispose()
}
}
deinit {
#if TRACE_RESOURCES
_ = Resources.decrementTotal()
#endif
}
}
final private class AmbSink<O: ObserverType>: Sink<O> {
typealias ElementType = O.E
typealias Parent = Amb<ElementType>
typealias AmbObserverType = AmbObserver<O>
private let _parent: Parent
private let _lock = RecursiveLock()
// state
private var _choice = AmbState.neither
init(parent: Parent, observer: O, cancel: Cancelable) {
self._parent = parent
super.init(observer: observer, cancel: cancel)
}
func run() -> Disposable {
let subscription1 = SingleAssignmentDisposable()
let subscription2 = SingleAssignmentDisposable()
let disposeAll = Disposables.create(subscription1, subscription2)
let forwardEvent = { (o: AmbObserverType, event: Event<ElementType>) -> Void in
self.forwardOn(event)
if event.isStopEvent {
self.dispose()
}
}
let decide = { (o: AmbObserverType, event: Event<ElementType>, me: AmbState, otherSubscription: Disposable) in
self._lock.performLocked {
if self._choice == .neither {
self._choice = me
o._sink = forwardEvent
o._cancel = disposeAll
otherSubscription.dispose()
}
if self._choice == me {
self.forwardOn(event)
if event.isStopEvent {
self.dispose()
}
}
}
}
let sink1 = AmbObserver(parent: self, cancel: subscription1) { o, e in
decide(o, e, .left, subscription2)
}
let sink2 = AmbObserver(parent: self, cancel: subscription1) { o, e in
decide(o, e, .right, subscription1)
}
subscription1.setDisposable(self._parent._left.subscribe(sink1))
subscription2.setDisposable(self._parent._right.subscribe(sink2))
return disposeAll
}
}
final private class Amb<Element>: Producer<Element> {
fileprivate let _left: Observable<Element>
fileprivate let _right: Observable<Element>
init(left: Observable<Element>, right: Observable<Element>) {
self._left = left
self._right = right
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
let sink = AmbSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| apache-2.0 | 623c6eb0589f4ac0d6308f9965de177a | 29.789809 | 145 | 0.599297 | 4.543233 | false | false | false | false |
dfuerle/kuroo | kuroo/Context.swift | 1 | 1347 | //
// Context.swift
// kuroo
//
// Copyright © 2016 Dmitri Fuerle. All rights reserved.
//
import UIKit
protocol SupportsContext {
var context: Context! { get set }
}
class Context {
let defaultFont = UIFont.systemFontSize
let tableHeaderFont = UIFont.systemFont(ofSize: 16.0)
let navigationItemFont = UIFont.systemFont(ofSize: 20)
let kuGreen = UIColor(red: 153.0/256.0, green: 204.0/256.0, blue: 153.0/256.0, alpha: 1)
let kuYellow = UIColor(red: 255.0/256.0, green: 205.0/256.0, blue: 99.0/256.0, alpha: 1)
let kuRed = UIColor(red: 194.0/256.0, green: 65.0/256.0, blue: 33.0/256.0, alpha: 1)
let kuLightGreen = UIColor(red: 234.0/256.0, green: 254.0/256.0, blue: 237.0/256.0, alpha: 1)
let kuLightRed = UIColor(red: 253.0/256.0, green: 236.0/256.0, blue: 236.0/256.0, alpha: 1)
let kuDarkGreen = UIColor(red: 79.0/256.0, green: 145.0/256.0, blue: 61.0/256.0, alpha: 1)
let kuDarkBlue = UIColor(red: 34.0/256.0, green: 24.0/256.0, blue: 222.0/256.0, alpha: 1)
let locationManager = LocationManager()
let addressBook = AddressBook()
var dataController = DataController()
let userSettings = UserSettings()
let iCloudController = ICloudController()
// MARK: - Init
init() {
addressBook.context = self
addressBook.buildContacts()
}
}
| gpl-2.0 | 26638fa21eb1a98e264f16ecfa18a542 | 33.512821 | 97 | 0.653046 | 3.024719 | false | false | false | false |
MoralAlberto/SlackWebAPIKit | Example/Tests/Integration/Channels/FindChannelUseCaseSpec.swift | 1 | 1922 | import Quick
import Nimble
import Alamofire
import RxSwift
@testable import SlackWebAPIKit
class FindChannelUseCaseSpec: QuickSpec {
class MockAPIClient: APIClientProtocol {
func execute(withURL url: URL?) -> Observable<[String: Any]> {
let json = readJSON(name: "apiclient.find.channel.succeed") as? [String: Any]
return Observable.from(optional: json)
}
}
override func spec() {
describe("\(String(describing: FindChannelUseCase.self)) Spec") {
context("check find user use case") {
var sut: FindChannelUseCaseProtocol!
let mockAPIClient = MockAPIClient()
let remoteDatasource = ChannelDatasource(apiClient: mockAPIClient)
let repository = ChannelRepository(remoteDatasource: remoteDatasource)
let disposeBag = DisposeBag()
beforeEach {
sut = FindChannelUseCase(repository: repository)
}
it("channel is found") {
sut.execute(channel: "general").subscribe(onNext: { channel in
expect(channel.id).to(equal("C6G3ZN7MX"))
expect(channel.name).to(equal("general"))
expect(channel.numMembers).to(beNil())
expect(channel.topic?.value).to(equal("Company-wide announcements and work-based matters"))
}).addDisposableTo(disposeBag)
}
it("channel is NOT found") {
sut.execute(channel: "generaal").subscribe(onError: { error in
expect(error as? ChannelDatasourceError).to(equal(ChannelDatasourceError.channelNotFound))
}).addDisposableTo(disposeBag)
}
}
}
}
}
| mit | dcad9aa34ba3c6b5be5828244c452e67 | 39.041667 | 115 | 0.548907 | 5.444759 | false | false | false | false |
CatchChat/Yep | Yep/Views/Cells/DiscoverCardUser/MiniCardSkillLayout.swift | 1 | 2928 | //
// MiniCardSkillLayout.swift
// Yep
//
// Created by zhowkevin on 15/10/12.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
final class MiniCardSkillLayout: UICollectionViewFlowLayout {
var scrollUpAction: ((progress: CGFloat) -> Void)?
let leftEdgeInset: CGFloat = 0
override func prepareLayout() {
self.minimumLineSpacing = 5
}
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let layoutAttributes = super.layoutAttributesForElementsInRect(rect)
// 先按照每个 item 的 centerY 分组
var rowCollections = [CGFloat: [UICollectionViewLayoutAttributes]]()
if let layoutAttributes = layoutAttributes {
for attributes in layoutAttributes {
let centerY = CGRectGetMidY(attributes.frame)
if let rowCollection = rowCollections[centerY] {
var rowCollection = rowCollection
rowCollection.append(attributes)
rowCollections[centerY] = rowCollection
} else {
rowCollections[centerY] = [attributes]
}
}
}
// 再调整每一行的 item 的 frame
for (_, rowCollection) in rowCollections {
//let rowItemsCount = rowCollection.count
// 每一行总的 InteritemSpacing
//let aggregateInteritemSpacing = minimumInteritemSpacing * CGFloat(rowItemsCount - 1)
// 每一行所有 items 的宽度
var aggregateItemsWidth: CGFloat = 0
for attributes in rowCollection {
aggregateItemsWidth += CGRectGetWidth(attributes.frame)
}
// 计算出有效的 width 和需要偏移的 offset
//let alignmentWidth = aggregateItemsWidth + aggregateInteritemSpacing
//let alignmentOffsetX = (CGRectGetWidth(collectionView!.bounds) - alignmentWidth) / 2
// 调整每个 item 的 origin.x 即可
var previousFrame = CGRectZero
for attributes in rowCollection {
var itemFrame = attributes.frame
if CGRectEqualToRect(previousFrame, CGRectZero) {
itemFrame.origin.x = leftEdgeInset
} else {
itemFrame.origin.x = CGRectGetMaxX(previousFrame) + minimumInteritemSpacing
}
attributes.frame = itemFrame
previousFrame = itemFrame
}
}
return layoutAttributes
}
override func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool {
return true
}
}
| mit | d47c7b27becdd2d44bf16c13607b96b1 | 31.895349 | 106 | 0.563097 | 6.343049 | false | false | false | false |
deltaDNA/ios-sdk | DeltaDNA/DDNAConsentTracker.swift | 1 | 3446 | import Foundation
@objc public enum ConsentStatus: Int {
case unknown = 0, notRequired, requiredButUnchecked, consentGiven, consentDenied
}
@objc public class DDNAConsentTracker: NSObject {
@objc public var piplUseStatus: ConsentStatus
@objc public var piplExportStatus: ConsentStatus
private let userDefaultsInstance: UserDefaults
private let geoIPNetworkClient: GeoIpNetworkClientProtocol
private let piplUseStatusKey = "ddnaPiplUseStatus"
private let piplExportStatusKey = "ddnaPiplExportStatus"
@objc public convenience override init() {
self.init(userDefaults: UserDefaults.standard, geoIpNetworkClient: GeoIpNetworkClient())
}
init(userDefaults: UserDefaults, geoIpNetworkClient: GeoIpNetworkClientProtocol) {
self.userDefaultsInstance = userDefaults
self.geoIPNetworkClient = geoIpNetworkClient
piplUseStatus = ConsentStatus(rawValue: userDefaultsInstance.integer(forKey: piplUseStatusKey)) ?? .unknown
piplExportStatus = ConsentStatus(rawValue: userDefaultsInstance.integer(forKey: piplExportStatusKey)) ?? .unknown
super.init()
}
@objc public func hasCheckedForConsent() -> Bool {
let checkedConsentStatuses: [ConsentStatus] = [.notRequired, .consentGiven, .consentDenied]
return checkedConsentStatuses.contains(piplUseStatus)
&& checkedConsentStatuses.contains(piplExportStatus)
}
@objc public func isPiplConsentRequired(callback: @escaping (Bool, Error?) -> ()) {
if hasCheckedForConsent() {
callback(false, nil)
return
}
geoIPNetworkClient.fetchGeoIpResponse { response, error in
if let error = error {
NSLog("Unable to check for the required consents to use DeltaDNA in this region because \(error.localizedDescription).")
callback(false, error)
return
}
if let response = response {
let isConsentNeeded = response.identifier == "pipl"
let consentStatus = isConsentNeeded ? ConsentStatus.requiredButUnchecked : ConsentStatus.notRequired
self.piplUseStatus = consentStatus
self.piplExportStatus = consentStatus
callback(isConsentNeeded, nil)
} else {
NSLog("Unable to check for the required consents to use DeltaDNA in this region because the response was empty.")
callback(false, URLError(.badServerResponse))
}
}
}
@objc public func setPiplUseConsent(_ isConsentGiven: Bool) {
piplUseStatus = isConsentGiven ? .consentGiven : .consentDenied
userDefaultsInstance.set(piplUseStatus.rawValue, forKey: piplUseStatusKey)
}
@objc public func setPiplExportConsent(_ isConsentGiven: Bool) {
piplExportStatus = isConsentGiven ? .consentGiven : .consentDenied
userDefaultsInstance.set(piplExportStatus.rawValue, forKey: piplExportStatusKey)
}
@objc public func allConsentsAreMet() -> Bool {
return (piplUseStatus == .consentGiven || piplUseStatus == .notRequired)
&& (piplExportStatus == .consentGiven || piplExportStatus == .notRequired)
}
@objc public func isConsentDenied() -> Bool {
return piplUseStatus == .consentDenied || piplExportStatus == .consentDenied
}
}
| apache-2.0 | edae43f4e4d2c5105d4366fe6b789bb1 | 42.620253 | 136 | 0.676146 | 4.637954 | false | false | false | false |
jonbrown21/Seafood-Guide-iOS | Seafood Guide/Lingo/ViewControllers/DetailLingoViewController.swift | 1 | 7158 | // Converted to Swift 5.1 by Swiftify v5.1.26565 - https://objectivec2swift.com/
//
// DetailLingoViewController.swift
// Seafood Guide
//
// Created by Jon Brown on 9/2/14.
// Copyright (c) 2014 Jon Brown Designs. All rights reserved.
//
import MessageUI
import ProgressHUD
import UIKit
@objcMembers
class DetailLingoViewController: UITableViewController, UIWebViewDelegate, MFMailComposeViewControllerDelegate {
var str = ""
var item: Lingo?
override init(style: UITableView.Style) {
super.init(style: .grouped)
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
title = item?.titlenews
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 2
} else {
return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell? = nil
if indexPath.section == 0 {
if indexPath.row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "CellType1")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "CellType1")
}
cell?.textLabel?.text = item?.titlenews
cell?.selectionStyle = .none
} else if indexPath.row == 1 {
cell = tableView.dequeueReusableCell(withIdentifier: "CellType2")
if cell == nil {
cell = UITableViewCell(style: .default, reuseIdentifier: "CellType2")
}
cell?.textLabel?.text = item?.descnews
cell?.textLabel?.lineBreakMode = .byWordWrapping
cell?.textLabel?.numberOfLines = 0
cell?.textLabel?.font = UIFont(name: "Helvetica", size: 17.0)
cell?.selectionStyle = .none
}
} else if indexPath.section == 1 {
if indexPath.row == 0 {
cell = tableView.dequeueReusableCell(withIdentifier: "CellType6")
if cell == nil {
cell = UITableViewCell(style: .subtitle, reuseIdentifier: "CellType6")
}
cell?.textLabel?.text = "Email to a friend"
//cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
}
return cell!
}
// MARK: - Table view delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 1 {
if indexPath.row == 0 {
sendEmail()
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 && indexPath.row == 1 {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
let attributes = [
NSAttributedString.Key.font: UIFont.systemFont(ofSize: 17),
NSAttributedString.Key.paragraphStyle: paragraphStyle
]
let textRect = item?.descnews?.boundingRect(with: CGSize(width: 290 - (10 * 2), height: 200000.0), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let height = Float(textRect?.size.height ?? 0.0)
return CGFloat(height + (2 * 2))
}
return 44
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if section == 0 {
return "Lingo Information"
} else if section == 1 {
return "Share"
}
return nil
}
override func viewDidAppear(_ animated: Bool) {
navigationItem.hidesBackButton = false
}
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
switch result {
case .cancelled:
ProgressHUD.showError("Email Not Sent")
case .saved:
ProgressHUD.showSuccess("Email Saved!")
case .sent:
ProgressHUD.showSuccess("Email Sent!")
case .failed:
ProgressHUD.showError("Email Not Sent")
default:
ProgressHUD.showError("Email Not Sent")
}
dismiss(animated: true)
}
func sendEmail() {
str = item?.descnews ?? ""
str = (str as NSString).substring(to: min(1165, str.count))
let one = item?.titlenews
let two = item?.descnews
let All = "Fish Name: \(one ?? "")\n\nType: \(two ?? "")\n\n\nDescription:\n\(str)"
if MFMailComposeViewController.canSendMail() {
let mailer = MFMailComposeViewController()
mailer.mailComposeDelegate = self
mailer.setSubject("Food & Water Watch - Check This Out: \(one ?? "")")
let toRecipients = [config.getMail()]
mailer.setToRecipients(toRecipients)
let emailBody = All
mailer.setMessageBody(emailBody, isHTML: false)
present(mailer, animated: true)
} else {
let alert = UIAlertController(title: "Failure", message: "Your device doesn't support the composer sheet", preferredStyle: .alert)
let noButton = UIAlertAction(title: "Dismiss", style: .default, handler: { action in
//Handle no, thanks button
self.presentedViewController?.dismiss(animated: false)
})
alert.addAction(noButton)
present(alert, animated: true)
}
}
func createButton(withFrame frame: CGRect, andLabel label: String?) -> UIButton? {
let button = UIButton(frame: frame)
button.setTitleShadowColor(UIColor.black, for: .normal)
button.titleLabel?.shadowOffset = CGSize(width: 0, height: -1)
button.titleLabel?.font = UIFont.boldSystemFont(ofSize: 18)
button.setTitle(label, for: .normal)
button.setTitleColor(UIColor.white, for: .normal)
button.layer.borderWidth = 1.0
button.layer.borderColor = UIColor.white.cgColor
button.layer.masksToBounds = true
button.layer.cornerRadius = 4.0 //when radius is 0, the border is a rectangle
button.layer.borderWidth = 1.0
return button
}
func closeView() {
//[self dismissModalViewControllerAnimated:YES];
dismiss(animated: true)
navigationController?.popViewController(animated: true)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| mit | f479c9146953731b1167c672e2b09fae | 31.243243 | 182 | 0.59444 | 5.065817 | false | false | false | false |
apple/swift | test/Interop/SwiftToCxx/initializers/init-in-cxx.swift | 2 | 7641 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend %s -typecheck -module-name Init -clang-header-expose-decls=all-public -emit-clang-header-path %t/inits.h
// RUN: %FileCheck %s < %t/inits.h
// RUN: %check-interop-cxx-header-in-clang(%t/inits.h -Wno-unused-function)
// RUN: %target-swift-frontend %s -typecheck -module-name Init -clang-header-expose-decls=all-public -swift-version 5 -emit-clang-header-path %t/inits2.h
// RUN: %FileCheck %s < %t/inits2.h
// CHECK: SWIFT_EXTERN void * _Nonnull $s4Init9BaseClassCyACSi_SitcfC(ptrdiff_t x, ptrdiff_t y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // init(_:_:)
// CHECK-NEXT: SWIFT_EXTERN void * _Nonnull $s4Init9BaseClassCyACSicfC(ptrdiff_t x, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // init(_:)
// CHECK-NEXT: SWIFT_EXTERN void * _Nonnull $s4Init12DerivedClassCyACSi_SitcfC(ptrdiff_t x, ptrdiff_t y, SWIFT_CONTEXT void * _Nonnull _self) SWIFT_NOEXCEPT SWIFT_CALL; // init(_:_:)
// CHECK: SWIFT_EXTERN struct swift_interop_returnStub_Init_uint32_t_0_4 $s4Init16FirstSmallStructVACycfC(void) SWIFT_NOEXCEPT SWIFT_CALL; // init()
// CHECK-NEXT: SWIFT_EXTERN struct swift_interop_returnStub_Init_uint32_t_0_4 $s4Init16FirstSmallStructVyACSicfC(ptrdiff_t x) SWIFT_NOEXCEPT SWIFT_CALL; // init(_:)
// CHECK: SWIFT_EXTERN void $s4Init11LargeStructVACycfC(SWIFT_INDIRECT_RESULT void * _Nonnull) SWIFT_NOEXCEPT SWIFT_CALL; // init()
// CHECK-NEXT: SWIFT_EXTERN void $s4Init11LargeStructV1x1yACSi_AA010FirstSmallC0VtcfC(SWIFT_INDIRECT_RESULT void * _Nonnull, ptrdiff_t x, struct swift_interop_passStub_Init_uint32_t_0_4 y) SWIFT_NOEXCEPT SWIFT_CALL; // init(x:y:)
// CHECK: SWIFT_EXTERN struct swift_interop_returnStub_Init_[[PTRENC:void_ptr_0_[0-9]]] $s4Init28StructWithRefCountStoredPropVACycfC(void) SWIFT_NOEXCEPT SWIFT_CALL; // init()
// CHECK-NEXT: SWIFT_EXTERN struct swift_interop_returnStub_Init_[[PTRENC]] $s4Init28StructWithRefCountStoredPropV1xACSi_tcfC(ptrdiff_t x) SWIFT_NOEXCEPT SWIFT_CALL; // init(x:)
public struct FirstSmallStruct {
public let x: UInt32
public init() {
x = 42
}
public init(_ x: Int) {
self.x = UInt32(x)
}
private init(_ y: Float) {
fatalError("nope")
}
}
// CHECK: class FirstSmallStruct final {
// CHECK-NEXT: public:
// CHECK: inline FirstSmallStruct(FirstSmallStruct &&)
// CHECK-NEXT: inline uint32_t getX() const;
// CHECK-NEXT: static inline FirstSmallStruct init();
// CHECK-NEXT: static inline FirstSmallStruct init(swift::Int x);
// CHECK-NEXT: private:
public struct LargeStruct {
public let x1, x2, x3, x4, x5, x6: Int
public init () {
x1 = 0
x2 = 0
x3 = 0
x4 = 0
x5 = 0
x6 = 0
}
public init(x: Int, y: FirstSmallStruct) {
x1 = x
x2 = Int(y.x)
x3 = -x
x4 = 0
x5 = 11
x6 = x * Int(y.x)
}
}
// CHECK: class LargeStruct final {
// CHECK: inline swift::Int getX6() const;
// CHECK-NEXT: static inline LargeStruct init();
// CHECK-NEXT: static inline LargeStruct init(swift::Int x, const FirstSmallStruct& y);
// CHECK-NEXT: private:
private class RefCountedClass {
let x: Int
init(x: Int) {
self.x = x
print("create RefCountedClass \(x)")
}
deinit {
print("destroy RefCountedClass \(x)")
}
}
public struct StructWithRefCountStoredProp {
private let storedRef: RefCountedClass
public init() {
storedRef = RefCountedClass(x: -1)
}
public init(x: Int) {
storedRef = RefCountedClass(x: x)
}
}
// CHECK: static inline StructWithRefCountStoredProp init();
// CHECK-NEXT: static inline StructWithRefCountStoredProp init(swift::Int x);
public final class FinalClass {
public var prop: FirstSmallStruct
public init(_ prop: FirstSmallStruct) { self.prop = prop }
}
public class BaseClass {
public var x: Int
public init(_ x: Int, _ y: Int) { self.x = x + y }
public convenience init(_ x: Int) {
self.init(x, x * 2)
}
}
public class DerivedClass: BaseClass {
override public init(_ x: Int, _ y: Int) {
super.init(x + 1, y + 1)
}
}
public class DerivedClassTwo: BaseClass {
}
// CHECK: BaseClass BaseClass::init(swift::Int x, swift::Int y) {
// CHECK-NEXT: return _impl::_impl_BaseClass::makeRetained(_impl::$s4Init9BaseClassCyACSi_SitcfC(x, y, swift::TypeMetadataTrait<BaseClass>::getTypeMetadata()));
// CHECK: DerivedClass DerivedClass::init(swift::Int x, swift::Int y) {
// CHECK-NEXT: _impl::_impl_DerivedClass::makeRetained(_impl::$s4Init12DerivedClassCyACSi_SitcfC(x, y, swift::TypeMetadataTrait<DerivedClass>::getTypeMetadata()));
// CHECK: DerivedClassTwo DerivedClassTwo::init(swift::Int x, swift::Int y) {
// CHECK-NEXT: return _impl::_impl_DerivedClassTwo::makeRetained(_impl::$s4Init15DerivedClassTwoCyACSi_SitcfC(x, y, swift::TypeMetadataTrait<DerivedClassTwo>::getTypeMetadata()));
// CHECK: FinalClass FinalClass::init(const FirstSmallStruct& prop) {
// CHECK-NEXT: return _impl::_impl_FinalClass::makeRetained(_impl::$s4Init10FinalClassCyAcA16FirstSmallStructVcfC(_impl::swift_interop_passDirect_Init_uint32_t_0_4(_impl::_impl_FirstSmallStruct::getOpaquePointer(prop)), swift::TypeMetadataTrait<FinalClass>::getTypeMetadata()));
// CHECK: inline uint32_t FirstSmallStruct::getX() const {
// CHECK-NEXT: return _impl::$s4Init16FirstSmallStructV1xs6UInt32Vvg(_impl::swift_interop_passDirect_Init_uint32_t_0_4(_getOpaquePointer()));
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct FirstSmallStruct::init() {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Init_uint32_t_0_4(result, _impl::$s4Init16FirstSmallStructVACycfC());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline FirstSmallStruct FirstSmallStruct::init(swift::Int x) {
// CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Init_uint32_t_0_4(result, _impl::$s4Init16FirstSmallStructVyACSicfC(x));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline LargeStruct LargeStruct::init() {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s4Init11LargeStructVACycfC(result);
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline LargeStruct LargeStruct::init(swift::Int x, const FirstSmallStruct& y) {
// CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::$s4Init11LargeStructV1x1yACSi_AA010FirstSmallC0VtcfC(result, x, _impl::swift_interop_passDirect_Init_uint32_t_0_4(_impl::_impl_FirstSmallStruct::getOpaquePointer(y)));
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK: inline StructWithRefCountStoredProp StructWithRefCountStoredProp::init() {
// CHECK-NEXT: return _impl::_impl_StructWithRefCountStoredProp::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Init_[[PTRENC]](result, _impl::$s4Init28StructWithRefCountStoredPropVACycfC());
// CHECK-NEXT: });
// CHECK-NEXT: }
// CHECK-NEXT: inline StructWithRefCountStoredProp StructWithRefCountStoredProp::init(swift::Int x) {
// CHECK-NEXT: return _impl::_impl_StructWithRefCountStoredProp::returnNewValue([&](char * _Nonnull result) {
// CHECK-NEXT: _impl::swift_interop_returnDirect_Init_[[PTRENC]](result, _impl::$s4Init28StructWithRefCountStoredPropV1xACSi_tcfC(x));
// CHECK-NEXT: });
// CHECK-NEXT: }
| apache-2.0 | 65da38fc8b94c2f6fadacf76a47411e4 | 42.414773 | 278 | 0.697291 | 3.514719 | false | false | false | false |
RyanTech/cannonball-ios | Cannonball/NativeAdCell.swift | 3 | 2185 | //
// Copyright (C) 2014 Twitter, Inc. and other 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.
//
import UIKit
import MoPub
class NativeAdCell: UITableViewCell, MPNativeAdRendering {
// MARK: Properties
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var mainTextLabel: UILabel!
@IBOutlet weak var callToActionButton: UIButton!
@IBOutlet weak var mainImageView: UIImageView!
@IBOutlet weak var iconImageView: UIImageView!
@IBOutlet weak var containerView: UIView!
func layoutAdAssets(adObject: MPNativeAd!) {
// Load ad assets.
adObject.loadTitleIntoLabel(titleLabel)
adObject.loadTextIntoLabel(mainTextLabel)
adObject.loadCallToActionTextIntoLabel(callToActionButton.titleLabel)
adObject.loadImageIntoImageView(mainImageView)
adObject.loadIconIntoImageView(iconImageView)
// Decorate the call to action button.
callToActionButton.layer.masksToBounds = false
callToActionButton.layer.borderColor = callToActionButton.titleLabel?.textColor.CGColor
callToActionButton.layer.borderWidth = 2
callToActionButton.layer.cornerRadius = 6
// Decorate the ad container.
containerView.layer.cornerRadius = 6
// Add the background color to the main view.
backgroundColor = UIColor.cannonballBrownColor()
}
class func sizeWithMaximumWidth(maximumWidth: CGFloat) -> CGSize {
return CGSizeMake(maximumWidth, maximumWidth)
}
// Return the nib used for the native ad.
class func nibForAd() -> UINib! {
return UINib(nibName: "NativeAdCell", bundle: nil)
}
}
| apache-2.0 | 02740567b66570cc66c6988604c2629c | 32.106061 | 95 | 0.719451 | 4.770742 | false | false | false | false |
baiyidjp/SwiftWB | SwiftWeibo/SwiftWeibo/Classes/Tools(工具)/Emoticon/EmoticonView/JPEmoticonTipView.swift | 1 | 1835 | //
// JPEmoticonTipView.swift
// SwiftWeibo
//
// Created by tztddong on 2016/12/15.
// Copyright © 2016年 dongjiangpeng. All rights reserved.
//
import UIKit
import pop
/// 长按表情弹出视图
class JPEmoticonTipView: UIImageView {
//之前选择的表情
fileprivate var preEmoticonModel: JPEmoticonModel?
//提示视图的模型
var emoticonModel: JPEmoticonModel? {
didSet {
if emoticonModel == preEmoticonModel {
return
}
//记录Model
preEmoticonModel = emoticonModel
//赋值
tipButton.setTitle(emoticonModel?.emoji, for: .normal)
tipButton.setImage(emoticonModel?.image, for: .normal)
//添加pop动画
let animation: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
animation.fromValue = 30
animation.toValue = 8
animation.springSpeed = 20
animation.springBounciness = 20
tipButton.layer.pop_add(animation, forKey: nil)
}
}
fileprivate lazy var tipButton = UIButton()
init() {
let image = UIImage(named: "emoticon_keyboard_magnifier")
super.init(image: image)
//锚点
layer.anchorPoint = CGPoint(x: 0.5, y: 1.2)
//图片
tipButton.layer.anchorPoint = CGPoint(x: 0.5, y: 0)
tipButton.frame = CGRect(x: 0, y: 8, width: 36, height: 36)
tipButton.center.x = bounds.width*0.5
tipButton.titleLabel?.font = UIFont.systemFont(ofSize: 32)
addSubview(tipButton)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 5344f5469ba9bac42f6f9edbb477b318 | 25.727273 | 101 | 0.573696 | 4.334152 | false | false | false | false |
airbnb/lottie-ios | Sources/Private/Utility/Primitives/UnitBezier.swift | 3 | 3830 | // Copyright (C) 2008 Apple Inc. All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import CoreGraphics
import Foundation
/// Defines a cubic-bezier where the endpoints are (0, 0) and (1, 1)
///
/// The main use case is computing the progress of an animation at a given percent completion. For instance,
/// for a linear animation, the expected progress at `0.5` is `0.5`.
///
/// - Note: This is a Swift port of [Apple's WebKit code](
/// http://svn.webkit.org/repository/webkit/trunk/Source/WebCore/platform/graphics/UnitBezier.h
/// )
///
struct UnitBezier {
// MARK: Lifecycle
init(controlPoint1: CGPoint, controlPoint2: CGPoint) {
cx = 3.0 * controlPoint1.x
bx = 3.0 * (controlPoint2.x - controlPoint1.x) - cx
ax = 1.0 - cx - bx
cy = 3.0 * controlPoint1.y
by = 3.0 * (controlPoint2.y - controlPoint1.y) - cy
ay = 1.0 - cy - by
}
// MARK: Internal
/// Computes the progress `y` value for a given `x` value
func value(for x: CGFloat, epsilon: CGFloat) -> CGFloat {
sampleCurveY(solveCurveX(x, epsilon: epsilon))
}
// MARK: Private
private let ax: CGFloat
private let bx: CGFloat
private let cx: CGFloat
private let ay: CGFloat
private let by: CGFloat
private let cy: CGFloat
/// Compute `x(t)` for a given `t`
private func sampleCurveX(_ t: CGFloat) -> CGFloat {
// `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
((ax * t + bx) * t + cx) * t
}
/// Compute `y(t)` for a given `t`
private func sampleCurveY(_ t: CGFloat) -> CGFloat {
((ay * t + by) * t + cy) * t
}
/// Compute `x'(t)` for a given `t`
private func sampleCurveDerivativeX(_ t: CGFloat) -> CGFloat {
(3.0 * ax * t + 2.0 * bx) * t + cx
}
/// Given an `x` value solve for the parametric value `t`
private func solveCurveX(_ x: CGFloat, epsilon: CGFloat) -> CGFloat {
var t0, t1, t2, x2, d2: CGFloat
// First try a few iterations of Newton-Raphson -- normally very fast.
t2 = x
for _ in 0..<8 {
x2 = sampleCurveX(t2) - x
guard abs(x2) >= epsilon else { return t2 }
d2 = sampleCurveDerivativeX(t2)
guard abs(d2) >= 1e-6 else { break }
t2 = t2 - x2 / d2
}
// Fall back to the bisection method for reliability.
t0 = 0.0
t1 = 1.0
t2 = x
guard t2 >= t0 else { return t0 }
guard t2 <= t1 else { return t1 }
while t0 < t1 {
x2 = sampleCurveX(t2)
guard abs(x2 - x) >= epsilon else { return t2 }
if x > x2 {
t0 = t2
} else {
t1 = t2
}
t2 = (t1 - t0) * 0.5 + t0
}
return t2
}
}
| apache-2.0 | afb9aaaea3228a3497d258eb753fdf2e | 32.304348 | 108 | 0.651958 | 3.576097 | false | false | false | false |
146BC/StyleKit | StyleKit/Helpers/FontHelper.swift | 1 | 730 | import Foundation
public struct FontHelper {
public static func parseFont(_ font: String) -> UIFont? {
let fontString = font.components(separatedBy: ":")
if let size = NumberFormatter().number(from: fontString.last!) as? CGFloat {
if fontString.count == 2 {
if let font = UIFont(name: fontString.first!, size: size) {
return font
} else {
SKLogger.error("Font \(font) not found, using system font.")
return UIFont.systemFont(ofSize: size)
}
} else {
return nil
}
} else {
return nil
}
}
}
| mit | f053f3aec3d02cd5dd2c5fae41391132 | 28.2 | 84 | 0.479452 | 5.069444 | false | false | false | false |
zwaldowski/ParksAndRecreation | Swift-2/Geometry.playground/Sources/Utilities.swift | 1 | 612 | import UIKit
import Swift
// MARK: Assertions
func assertMainThread(file: StaticString = __FILE__, line: UInt = __LINE__) {
assert(NSThread.isMainThread(), "This code must be called on the main thread.", file: file, line: line)
}
// MARK: Version Checking
public struct Version {
public static let isiOS9 = floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_8_3
public static let isiOS8 = floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1 && !isiOS9
public static let isiOS7 = floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1 && !isiOS8
}
| mit | 33fbb1f2233b044750b6175f79cc0d83 | 37.25 | 110 | 0.748366 | 4.191781 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Value Info Processors/FileInfoProcessor.swift | 1 | 4905 | //
// FileInfoProcessor.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
class FileInfoProcessor {
// MARK: -
// MARK: Variables
let fileURL: URL?
let fileUTI: String
var fileInfoVar: FileInfo?
var fileAttributes: [FileAttributeKey: Any]?
var fileTitle: String?
var fileDataVar: Data?
// MARK: -
// MARK: Initialization
init?(data: Data, fileInfo: [String: Any]) {
// File UTI
if let fileUTI = fileInfo[FileInfoKey.fileUTI] as? String {
self.fileUTI = fileUTI
} else { return nil }
// File DataVar
self.fileDataVar = data
// File URL
if let filePath = fileInfo[FileInfoKey.fileURL] as? String {
self.fileURL = URL(fileURLWithPath: filePath)
self.fileTitle = self.fileURL?.lastPathComponent
} else {
self.fileURL = nil
self.fileTitle = nil
}
// File Info
if let fileInfoDict = fileInfo[FileInfoKey.fileInfoView] as? [String: Any] {
if let fileInfo = FileInfo(infoDict: fileInfoDict, backupIcon: NSWorkspace.shared.icon(forFileType: self.fileUTI)) {
self.fileInfoVar = fileInfo
} else {
Log.shared.error(message: "Failed to create FileInfo from dictionary: \(fileInfoDict)", category: String(describing: self))
}
}
}
init(fileURL: URL) {
// Restore
// File URL
self.fileURL = fileURL
// File UTI
if let unmanagedFileUTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileURL.pathExtension as CFString, nil) {
self.fileUTI = unmanagedFileUTI.takeRetainedValue() as String
} else {
self.fileUTI = kUTTypeItem as String
}
// File Attributes
self.fileAttributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path)
// File Title
self.fileTitle = fileURL.lastPathComponent
}
// MARK: -
// MARK: Functions
func fileData() -> Data? {
if let fileURL = self.fileURL {
return try? Data(contentsOf: fileURL)
} else {
return self.fileDataVar
}
}
func fileInfoDict() -> [String: Any] {
var fileInfoDict = [String: Any]()
// File ITU
fileInfoDict[FileInfoKey.fileUTI] = self.fileUTI
// File URL
if let fileURL = self.fileURL {
fileInfoDict[FileInfoKey.fileURL] = fileURL.path
}
// File Attributes
if let fileAttributes = self.fileAttributes {
fileInfoDict[FileInfoKey.fileAttributes] = fileAttributes
}
// File Info
let fileInfo = self.fileInfo()
fileInfoDict[FileInfoKey.fileInfoView] = fileInfo.infoDict()
return fileInfoDict
}
func fileInfo() -> FileInfo {
if let fileInfoVar = self.fileInfoVar {
return fileInfoVar
} else {
var title = ""
var topLabel = ""
var topContent = ""
var centerLabel: String?
var centerContent: String?
var icon: NSImage?
if let fileURL = self.fileURL {
// Title
title = self.fileTitle ?? fileURL.lastPathComponent
// Top
topLabel = NSLocalizedString("Path", comment: "")
topContent = fileURL.path
// Center
if
let fileAttributes = self.fileAttributes,
let fileSize = fileAttributes[.size] as? Int64 {
centerLabel = NSLocalizedString("Size", comment: "")
centerContent = ByteCountFormatter.string(fromByteCount: fileSize, countStyle: ByteCountFormatter.CountStyle.file)
}
// Icon
icon = NSWorkspace.shared.icon(forFileType: self.fileUTI)
// icon = NSWorkspace.shared.icon(forFile: fileURL.path)
}
// FIXME: Need to fix defaults here
self.fileInfoVar = FileInfo(title: title,
topLabel: topLabel,
topContent: topContent,
topError: false,
centerLabel: centerLabel,
centerContent: centerContent,
centerError: false,
bottomLabel: nil,
bottomContent: nil,
bottomError: false,
icon: icon)
return self.fileInfoVar!
}
}
}
| mit | efe3083dbe93378216edf76b8b6155de | 29.459627 | 143 | 0.531811 | 5.267454 | false | false | false | false |
alexsosn/ConvNetSwift | ConvNetSwift/convnet-swift/VolUtil.swift | 1 | 6736 |
import Foundation
// Volume utilities
// intended for use with data augmentation
// crop is the size of output
// dx,dy are offset wrt incoming volume, of the shift
// fliplr is boolean on whether we also want to flip left<->right
func augment(_ V: Vol, crop: Int, dx: Int?, dy: Int?, fliplr: Bool = false) -> Vol {
// note assumes square outputs of size crop x crop
let dx = dx ?? RandUtils.randi(0, V.sx - crop)
let dy = dy ?? RandUtils.randi(0, V.sy - crop)
// randomly sample a crop in the input volume
var W: Vol
if crop != V.sx || dx != 0 || dy != 0 {
W = Vol(sx: crop, sy: crop, depth: V.depth, c: 0.0)
for x in 0 ..< crop {
for y in 0 ..< crop {
if x+dx<0 || x+dx>=V.sx || y+dy<0 || y+dy>=V.sy {
continue // oob
}
for d in 0 ..< V.depth {
W.set(x: x, y: y, d: d, v: V.get(x: x+dx, y: y+dy, d: d)) // copy data over
}
}
}
} else {
W = V
}
if fliplr {
// flip volume horizontally
let W2 = W.cloneAndZero()
for x in 0 ..< W.sx {
for y in 0 ..< W.sy {
for d in 0 ..< W.depth {
W2.set(x: x, y: y, d: d, v: W.get(x: W.sx - x - 1, y: y, d: d)) // copy data over
}
}
}
W = W2 //swap
}
return W
}
import UIKit
import CoreGraphics
// img is a DOM element that contains a loaded image
// returns a Vol of size (W, H, 4). 4 is for RGBA
//func img_to_vol(img: UIImage, convert_grayscale: Bool = false) -> Vol? {
//
//// guard let uiimage = UIImage(contentsOfFile: "/PATH/TO/image.png") else {
//// print("error: no image found on provided path")
//// return nil
//// }
// var image = img.CGImage
//
//
// let width = CGImageGetWidth(image)
// let height = CGImageGetHeight(image)
// let colorspace = CGColorSpaceCreateDeviceRGB()
// let bytesPerRow = (4 * width)
// let bitsPerComponent: Int = 8
// var pixels = UnsafeMutablePointer<Void>(malloc(width*height*4))
//
//
// var context = CGBitmapContextCreate(
// pixels,
// width,
// height,
// bitsPerComponent,
// bytesPerRow,
// colorspace,
// CGBitmapInfo().rawValue)
//
// CGContextDrawImage(context, CGRectMake(0, 0, CGFloat(width), CGFloat(height)), image)
//
//
// for x in 0...width {
// for y in 0...height {
// //Here is your raw pixels
// let offset = 4*((Int(width) * Int(y)) + Int(x))
// let alpha = pixels[offset]
// let red = pixels[offset+1]
// let green = pixels[offset+2]
// let blue = pixels[offset+3]
// }
// }
// ////////////////////////////
// // prepare the input: get pixels and normalize them
// var pv = []
// for i in 0 ..< width*height {
//
// pv.append(p[i]/255.0-0.5) // normalize image pixels to [-0.5, 0.5]
// }
//
// var x = Vol(W, H, 4, 0.0) //input volume (image)
// x.w = pv
//
// if convert_grayscale {
// // flatten into depth=1 array
// var x1 = Vol(width, height, 1, 0.0)
// for i in 0 ..< width {
//
// for j in 0 ..< height {
//
// x1.set(i, j, 0, x.get(i,j,0))
// }
// }
// x = x1
// }
//
// return x
//}
extension Vol {
func denormalize(_ pixelChannel: Double) -> UInt8{
return UInt8(pixelChannel * 255.0)
}
func toImage() -> UIImage? {
let intDenormArray: [UInt8] = w.map { (elem: Double) -> UInt8 in
return denormalize(elem)
}
let width = sx
let height = sy
let components = depth
let bitsPerComponent: Int = 8
let bitsPerPixel = bitsPerComponent * components
let bytesPerRow = (components * width)
let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let providerRef = CGDataProvider(
data: Data(bytes: UnsafePointer<UInt8>(intDenormArray), count: intDenormArray.count * components) as CFData
)
guard let cgim = CGImage(
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bitsPerPixel: bitsPerPixel,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo,
provider: providerRef!,
decode: nil,
shouldInterpolate: false,
intent: .defaultIntent
) else {
return nil
}
let newImage = UIImage(cgImage: cgim)
return newImage
}
}
extension UIImage {
func toVol(convert_grayscale: Bool = false) -> Vol? {
if convert_grayscale {
// TODO: implement
}
guard let image = cgImage else {
return nil
}
let width = image.width
let height = image.height
let components = 4
let bytesPerRow = (components * width)
let bitsPerComponent: Int = 8
let pixels = calloc(height * width, MemoryLayout<UInt32>.size)
let bitmapInfo: CGBitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let context = CGContext(
data: pixels,
width: width,
height: height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue)
context?.draw(image, in: CGRect(x: 0, y: 0, width: CGFloat(width), height: CGFloat(height)))
let dataCtxt = context?.data!
let data = Data(bytesNoCopy: UnsafeMutableRawPointer(dataCtxt)!, count: width*height*components, deallocator: .free)
var pixelMem = [UInt8](repeating: 0, count: data.count)
(data as NSData).getBytes(&pixelMem, length: data.count)
let doubleNormArray = pixelMem.map { (elem: UInt8) -> Double in
return normalize(elem)
}
let vol = Vol(width: width, height: height, depth: components, array: doubleNormArray)
return vol
}
fileprivate func normalize(_ pixelChannel: UInt8) -> Double{
return Double(pixelChannel)/255.0
}
}
| mit | 0de072192deac7e9e7c42929c4af679c | 29.479638 | 145 | 0.53177 | 4.019093 | false | false | false | false |
tarun-talentica/TalNet | Source/Vendors/AlamofireSpecific.swift | 2 | 1473 | //
// AlamofireImports.swift
// Pod-In-Playground
//
// Created by Tarun Sharma on 09/05/16.
// Copyright © 2016 Tarun Sharma. All rights reserved.
//
import Foundation
import Alamofire
public typealias NetworkManager = Alamofire.Manager
typealias ParameterEncoder = Alamofire.ParameterEncoding
public typealias VendorRequest = Alamofire.Request
public typealias VendorResponse = Alamofire.Response
public typealias VendorResponseSerializer = Alamofire.ResponseSerializer
//
//public extension StringSerializable {
// func serialize(from request:CancellableRequest,completionHandler: QueryResponse<String,NSError> -> Void) {
//
// request.innerCancellable?.vendorRequest?.responseString(encoding: self.encoding) {
// response in
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// completionHandler(convertResponseToQueryResult(response))
// }
// }
// }
//}
//
//public extension JsonSerializable {
// func serialize(from request:CancellableRequest,completionHandler: QueryResponse<AnyObject,NSError> -> Void) {
//
// request.innerCancellable?.vendorRequest?.responseJSON(options: self.jsonOptions) {
// response in
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// completionHandler(convertResponseToQueryResult(response))
// }
// }
// }
//} | mit | 170cb1b1d17221b98173903526d8992a | 34.071429 | 115 | 0.69769 | 4.515337 | false | false | false | false |
jkereako/MassStateKeno | Sources/Coordinators/DrawingsCoordinator.swift | 1 | 3560 | //
// DrawingsCoordinator.swift
// MassLotteryKeno
//
// Created by Jeff Kereakoglow on 5/24/19.
// Copyright © 2019 Alexis Digital. All rights reserved.
//
import Foundation
import Kringle
final class DrawingsCoordinator: RootCoordinator {
var rootViewController: UIViewController {
let drawingTableViewController = DrawingTableViewController()
refreshData(for: drawingTableViewController)
navigationController = UINavigationController(
rootViewController: drawingTableViewController
)
return navigationController!
}
private let networkClient: NetworkClient
private let dateFormatter: DateFormatter
private var navigationController: UINavigationController?
init(networkClient: NetworkClient, dateFormatter: DateFormatter) {
self.networkClient = networkClient
self.dateFormatter = dateFormatter
}
}
// MARK: - DrawingTableViewModelDelegate
extension DrawingsCoordinator: DrawingTableViewModelDelegate {
func refreshData(for viewController: DrawingTableViewController) {
let promise = networkClient.get(
MassLotteryEndpoint.todaysGames,
decodingResponseTo: GameDayContract.self,
query: ["buster": String(Date().timeIntervalSince1970)]
)
promise.then { [weak self] gameDayContract in
self?.buildViewModel(for: viewController, with: gameDayContract)
}.catch { [weak self] _ in
self?.showNetworkErrorAlert(on: viewController)
}
}
func didSelect(_ drawingViewModel: DrawingViewModel) {
let numberViewController = NumberViewController()
let numberViewModel = NumberViewModel(
drawing: drawingViewModel.model, dateFormatter: dateFormatter
)
numberViewModel.dataSource = numberViewController
numberViewController.viewModel = numberViewModel
navigationController?.show(numberViewController, sender: self)
}
}
// MARK: - Private Helpers
private extension DrawingsCoordinator {
func buildViewModel(for tableViewController: DrawingTableViewController,
with gameDayContract: GameDayContract) {
var drawingViewModels = [DrawingViewModel]()
let aDateFormatter = dateFormatter
gameDayContract.drawings.forEach { drawingContract in
let drawingModel = DrawingModel(
contract: drawingContract, dateFormatter: aDateFormatter
)
drawingViewModels.append(
DrawingViewModel(model: drawingModel, dateFormatter: aDateFormatter)
)
}
let refreshedDrawingTableViewModel = DrawingTableViewModel(
drawingViewModels: drawingViewModels
)
refreshedDrawingTableViewModel.dataSource = tableViewController
refreshedDrawingTableViewModel.delegate = self
tableViewController.delegate = refreshedDrawingTableViewModel
tableViewController.viewModel = refreshedDrawingTableViewModel
}
func showNetworkErrorAlert(on viewController: UIViewController) {
// Displays an alert if the promise is rejected
let alertController = UIAlertController(
title: "Network Error",
message: "We weren't able to load today's winning numbers. Please try again later.",
preferredStyle: .alert
)
alertController.addAction(UIAlertAction(title: "Okay", style: .cancel))
viewController.present(alertController, animated: true)
}
}
| mit | 53d78251017efa936e24dfc301cd5245 | 32.895238 | 96 | 0.697106 | 5.882645 | false | false | false | false |
insidegui/WWDC | WWDC/SessionViewModel.swift | 1 | 11385 | //
// SessionViewModel.swift
// WWDC
//
// Created by Guilherme Rambo on 22/04/17.
// Copyright © 2017 Guilherme Rambo. All rights reserved.
//
import Cocoa
import ConfCore
import RxRealm
import RxSwift
import RxCocoa
import RealmSwift
import PlayerUI
final class SessionViewModel {
let style: SessionsListStyle
var title: String
let session: Session
let sessionInstance: SessionInstance
let identifier: String
var webUrl: URL?
var imageUrl: URL?
let trackName: String
private var disposeBag = DisposeBag()
lazy var rxSession: Observable<Session> = {
return Observable.from(object: session)
}()
lazy var rxTranscriptAnnotations: Observable<List<TranscriptAnnotation>> = {
guard let annotations = session.transcript()?.annotations else {
return Observable.just(List<TranscriptAnnotation>())
}
return Observable.collection(from: annotations)
}()
lazy var rxSessionInstance: Observable<SessionInstance> = {
return Observable.from(object: sessionInstance)
}()
lazy var rxTitle: Observable<String> = {
return rxSession.map { $0.title }
}()
lazy var rxSubtitle: Observable<String> = {
return rxSession.map { SessionViewModel.subtitle(from: $0, at: $0.event.first) }
}()
lazy var rxTrackName: Observable<String> = {
return rxSession.map { $0.track.first?.name }.ignoreNil()
}()
lazy var rxSummary: Observable<String> = {
return rxSession.map { $0.summary }
}()
lazy var rxActionPrompt: Observable<String?> = {
guard sessionInstance.startTime > today() else { return Observable.just(nil) }
guard actionLinkURL != nil else { return Observable.just(nil) }
return rxSessionInstance.map { $0.actionLinkPrompt }
}()
var actionLinkURL: URL? {
guard let candidateURL = sessionInstance.actionLinkURL else { return nil }
return URL(string: candidateURL)
}
lazy var rxContext: Observable<String> = {
if self.style == .schedule {
return Observable.combineLatest(rxSession, rxSessionInstance).map {
SessionViewModel.context(for: $0.0, instance: $0.1)
}
} else {
return rxSession.map { SessionViewModel.context(for: $0) }
}
}()
lazy var rxFooter: Observable<String> = {
return rxSession.map { SessionViewModel.footer(for: $0, at: $0.event.first) }
}()
lazy var rxSessionType: Observable<SessionInstanceType> = {
return rxSession.map { $0.instances.first?.type }.ignoreNil()
}()
lazy var rxColor: Observable<NSColor> = {
return rxSession.map { SessionViewModel.trackColor(for: $0) }.ignoreNil()
}()
lazy var rxDarkColor: Observable<NSColor> = {
return rxSession.map { SessionViewModel.darkTrackColor(for: $0) }.ignoreNil()
}()
lazy var rxImageUrl: Observable<URL?> = {
return rxSession.map { SessionViewModel.imageUrl(for: $0) }
}()
lazy var rxWebUrl: Observable<URL?> = {
return rxSession.map { SessionViewModel.webUrl(for: $0) }
}()
lazy var rxIsDownloaded: Observable<Bool> = {
return rxSession.map { $0.isDownloaded }
}()
lazy var rxIsFavorite: Observable<Bool> = {
return Observable.collection(from: self.session.favorites.filter("isDeleted == false")).map { $0.count > 0 }
}()
lazy var rxIsCurrentlyLive: Observable<Bool> = {
guard self.sessionInstance.realm != nil else {
return Observable.just(false)
}
return rxSessionInstance.map { $0.isCurrentlyLive }
}()
lazy var rxIsLab: Observable<Bool> = {
guard self.sessionInstance.realm != nil else {
return Observable.just(false)
}
return rxSessionInstance.map { [.lab, .labByAppointment].contains($0.type) }
}()
lazy var rxPlayableContent: Observable<Results<SessionAsset>> = {
let playableAssets = self.session.assets(matching: [.streamingVideo, .liveStreamVideo])
return Observable.collection(from: playableAssets)
}()
lazy var rxCanBePlayed: Observable<Bool> = {
let validAssets = self.session.assets.filter("(rawAssetType == %@ AND remoteURL != '') OR (rawAssetType == %@ AND SUBQUERY(session.instances, $instance, $instance.isCurrentlyLive == true).@count > 0)", SessionAssetType.streamingVideo.rawValue, SessionAssetType.liveStreamVideo.rawValue)
let validAssetsObservable = Observable.collection(from: validAssets)
return validAssetsObservable.map { $0.count > 0 }
}()
lazy var rxDownloadableContent: Observable<Results<SessionAsset>> = {
let downloadableAssets = self.session.assets.filter("(rawAssetType == %@ AND remoteURL != '')", DownloadManager.downloadQuality.rawValue)
return Observable.collection(from: downloadableAssets)
}()
lazy var rxProgresses: Observable<Results<SessionProgress>> = {
let progresses = self.session.progresses.filter(NSPredicate(value: true))
return Observable.collection(from: progresses)
}()
lazy var rxRelatedSessions: Observable<Results<RelatedResource>> = {
// Return sessions with videos, or any session that hasn't yet occurred
let predicateFormat = "type == %@ AND (ANY session.assets.rawAssetType == %@ OR ANY session.instances.startTime >= %@)"
let relatedPredicate = NSPredicate(format: predicateFormat, RelatedResourceType.session.rawValue, SessionAssetType.streamingVideo.rawValue, today() as NSDate)
let validRelatedSessions = self.session.related.filter(relatedPredicate)
return Observable.collection(from: validRelatedSessions)
}()
convenience init?(session: Session) {
self.init(session: session, instance: nil, style: .videos)
}
init?(session: Session?, instance: SessionInstance?, style: SessionsListStyle) {
self.style = style
guard let session = session ?? instance?.session else { return nil }
guard let track = session.track.first ?? instance?.track.first else { return nil }
trackName = track.name
self.session = session
sessionInstance = instance ?? session.instances.first ?? SessionInstance()
title = session.title
identifier = session.identifier
imageUrl = SessionViewModel.imageUrl(for: session)
if let webUrlStr = session.asset(ofType: .webpage)?.remoteURL {
webUrl = URL(string: webUrlStr)
}
}
static func subtitle(from session: Session, at event: ConfCore.Event?) -> String {
guard let event = event else { return "" }
let year = Calendar.current.component(.year, from: event.startDate)
var name = event.name
/*
We want to make sure that WWDC events show the year
So we add it it not present.
*/
if name == "WWDC" {
name.append(" \(year)")
}
return "\(name) · Session \(session.number)"
}
static func focusesDescription(from focuses: [Focus], collapse: Bool) -> String {
var result: String
if focuses.count == 4 && collapse {
result = "All Platforms"
} else {
let separator = ", "
result = focuses.reduce("") { $0 + $1.name + separator }
result = result.trimmingCharacters(in: CharacterSet(charactersIn: separator))
}
return result
}
static func context(for session: Session, instance: SessionInstance? = nil) -> String {
if let instance = instance {
var result = timeFormatter.string(from: instance.startTime) + " - " + timeFormatter.string(from: instance.endTime)
result += " · " + instance.roomName
return result
} else {
let focusesArray = session.focuses.toArray()
let focuses = SessionViewModel.focusesDescription(from: focusesArray, collapse: true)
var result = session.track.first?.name ?? ""
if focusesArray.count > 0 {
result = "\(focuses) · " + result
}
return result
}
}
static func footer(for session: Session, at event: ConfCore.Event?) -> String {
guard let event = event else { return "" }
let focusesArray = session.focuses.toArray()
let allFocuses = SessionViewModel.focusesDescription(from: focusesArray, collapse: false)
var result = "\(event.name) · Session \(session.number)"
if (event.startDate...event.endDate).contains(today()), let date = session.instances.first?.startTime {
result += " · " + standardFormatted(date: date, withTimeZoneName: false)
}
if session.mediaDuration > 0, let duration = String(timestamp: session.mediaDuration) {
result += " · " + duration
}
if focusesArray.count > 0 {
result += " · \(allFocuses)"
}
return result
}
static func imageUrl(for session: Session) -> URL? {
if let instance = session.instances.first {
guard [.session, .lab, .labByAppointment].contains(instance.type) else {
return nil
}
}
let imageAsset = session.asset(ofType: .image)
guard let thumbnail = imageAsset?.remoteURL, let thumbnailUrl = URL(string: thumbnail) else { return nil }
return thumbnailUrl
}
static func webUrl(for session: Session) -> URL? {
guard let url = session.asset(ofType: .webpage)?.remoteURL else { return nil }
return URL(string: url)
}
static func trackColor(for session: Session) -> NSColor? {
guard let code = session.track.first?.lightColor else { return nil }
return NSColor.fromHexString(hexString: code)
}
static func darkTrackColor(for session: Session) -> NSColor? {
guard let code = session.track.first?.darkColor else { return nil }
return NSColor.fromHexString(hexString: code)
}
static let shortDayOfTheWeekFormatter: DateFormatter = {
let df = DateFormatter()
df.locale = Locale.current
df.timeZone = TimeZone.current
df.dateFormat = "E"
return df
}()
static let dayOfTheWeekFormatter: DateFormatter = {
let df = DateFormatter()
df.locale = Locale.current
df.timeZone = TimeZone.current
df.dateFormat = "EEEE"
return df
}()
static let timeFormatter: DateFormatter = {
let tf = DateFormatter()
tf.locale = Locale.current
tf.timeZone = TimeZone.current
tf.timeStyle = .short
return tf
}()
static var timeZoneNameSuffix: String {
if let name = TimeZone.current.localizedName(for: .shortGeneric, locale: Locale.current) {
return " " + name
} else {
return ""
}
}
static func standardFormatted(date: Date, withTimeZoneName: Bool) -> String {
let result = dayOfTheWeekFormatter.string(from: date) + ", " + timeFormatter.string(from: date)
return withTimeZoneName ? result + timeZoneNameSuffix : result
}
}
extension SessionViewModel: UserActivityRepresentable { }
extension SessionViewModel {
var isFavorite: Bool { session.isFavorite }
}
| bsd-2-clause | 80b255f79ccab3d3a8fbfe8f71a3fed7 | 31.321023 | 294 | 0.635581 | 4.470334 | false | false | false | false |
yrchen/edx-app-ios | Source/Stream.swift | 1 | 18376 | //
// Stream.swift
// edX
//
// Created by Akiva Leffert on 6/15/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
// Bookkeeping class for a listener of a stream
private class Listener<A> : Removable, Equatable, CustomStringConvertible {
private var removeAction : (Listener<A> -> Void)?
private var action : (Result<A> -> Void)?
init(action : Result<A> -> Void, removeAction : Listener<A> -> Void) {
self.action = action
self.removeAction = removeAction
}
func remove() {
self.removeAction?(self)
self.removeAction = nil
self.action = nil
}
var description : String {
let address = unsafeBitCast(self, UnsafePointer<Void>.self)
return NSString(format: "<%@: %p>", "\(self.dynamicType)", address) as String
}
}
private func == <A>(lhs : Listener<A>, rhs : Listener<A>) -> Bool {
/// We want to use pointer equality for equality since the main thing
/// we care about for listeners is are they the same instance so we can remove them
return lhs === rhs
}
public protocol StreamDependency : class, CustomStringConvertible {
var active : Bool {get}
}
// MARK: Reading Streams
// This should really be a protocol with Sink a concrete instantiation of that protocol
// But unfortunately Swift doesn't currently support generic protocols
// Revisit this if it ever does
private let backgroundQueue = NSOperationQueue()
/// A stream of values and errors. Note that, like all objects, a stream will get deallocated if it has no references.
public class Stream<A> : StreamDependency {
private let dependencies : [StreamDependency]
private(set) var lastResult : Result<A>?
public var description : String {
let deps = self.dependencies.map({ $0.description }).joinWithSeparator(", ")
let ls = self.listeners.map({ $0.description }).joinWithSeparator(", ")
let address = unsafeBitCast(self, UnsafePointer<Void>.self)
return NSString(format: "<%@: %p, deps = {%@}, listeners = {%@}>", "\(self.dynamicType)", address, deps, ls) as String
}
private var baseActive : Bool {
return false
}
public var active : Bool {
return dependencies.reduce(baseActive, combine: {$0 || $1.active} )
}
public var value : A? {
return lastResult?.value
}
public var error : NSError? {
return lastResult?.error
}
private var listeners : [Listener<A>] = []
/// Make a new stream.
///
/// - parameter dependencies: A list of objects that this stream will retain.
/// Typically this is a stream or streams that this object is listening to so that
/// they don't get deallocated.
private init(dependencies : [StreamDependency]) {
self.dependencies = dependencies
}
public convenience init() {
self.init(dependencies : [])
}
/// Seed a new stream with a constant value.
///
/// - parameter value: The initial value of the stream.
public convenience init(value : A) {
self.init()
self.lastResult = Success(value)
}
/// Seed a new stream with a constant error.
///
/// - parameter error: The initial error for the stream
public convenience init(error : NSError) {
self.init()
self.lastResult = Failure(error)
}
private func joinHandlers<A>(success success : A -> Void, failure : NSError -> Void, finally : (Void -> Void)?) -> Result<A> -> Void {
return {
switch $0 {
case let .Success(v):
success(v.value)
case let .Failure(e):
failure(e)
}
finally?()
}
}
/// Add a listener to a stream.
///
/// - parameter owner: The listener will automatically be removed when owner gets deallocated.
/// - parameter fireIfLoaded: If true then this will fire the listener immediately if the signal has already received a value.
/// - parameter action: The action to fire when the stream receives a result.
public func listen(owner : NSObject, fireIfAlreadyLoaded : Bool = true, action : Result<A> -> Void) -> Removable {
let listener = Listener(action: action) {[weak self] (listener : Listener<A>) in
if let listeners = self?.listeners, index = listeners.indexOf(listener) {
self?.listeners.removeAtIndex(index)
}
}
listeners.append(listener)
let removable = owner.oex_performActionOnDealloc {
listener.remove()
}
if let value = self.value where fireIfAlreadyLoaded {
action(Success(value))
}
else if let error = self.error where fireIfAlreadyLoaded {
action(Failure(error))
}
return BlockRemovable {
removable.remove()
listener.remove()
}
}
/// Add a listener to a stream.
///
/// - parameter owner: The listener will automatically be removed when owner gets deallocated.
/// - parameter fireIfLoaded: If true then this will fire the listener immediately if the signal has already received a value. If false the listener won't fire until a new result is supplied to the stream.
/// - parameter success: The action to fire when the stream receives a Success result.
/// - parameter failure: The action to fire when the stream receives a Failure result.
/// - parameter finally: An action that will be executed after both the success and failure actions
public func listen(owner : NSObject, fireIfAlreadyLoaded : Bool = true, success : A -> Void, failure : NSError -> Void, finally : (Void -> Void)? = nil) -> Removable {
return listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded, action: joinHandlers(success:success, failure:failure, finally:finally))
}
/// Add a listener to a stream. When the listener fires it will be removed automatically.
///
/// - parameter owner: The listener will automatically be removed when owner gets deallocated.
/// - parameter fireIfLoaded: If true then this will fire the listener immediately if the signal has already received a value. If false the listener won't fire until a new result is supplied to the stream.
/// - parameter success: The action to fire when the stream receives a Success result.
/// - parameter success: The action to fire when the stream receives a Failure result.
/// - parameter finally: An action that will be executed after both the success and failure actions
public func listenOnce(owner : NSObject, fireIfAlreadyLoaded : Bool = true, success : A -> Void, failure : NSError -> Void, finally : (Void -> Void)? = nil) -> Removable {
return listenOnce(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded, action : joinHandlers(success:success, failure:failure, finally:finally))
}
public func listenOnce(owner : NSObject, fireIfAlreadyLoaded : Bool = true, action : Result<A> -> Void) -> Removable {
let removable = listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded, action : action)
let followup = listen(owner, fireIfAlreadyLoaded: fireIfAlreadyLoaded,
action: {_ in
removable.remove()
}
)
return BlockRemovable {
removable.remove()
followup.remove()
}
}
/// - returns: A filtered stream based on the receiver that will only fire the first time a success value is sent. Use this if you want to capture a value and *not* update when the next one comes in.
public func firstSuccess() -> Stream<A> {
let sink = Sink<A>(dependencies: [self])
listen(sink.token) {[weak sink] result in
if sink?.lastResult?.isFailure ?? true {
sink?.send(result)
}
}
return sink
}
/// - returns: A filtered stream based on the receiver that won't fire on errors after a value is loaded. It will fire if a new value comes through after a value is already loaded.
public func dropFailuresAfterSuccess() -> Stream<A> {
let sink = Sink<A>(dependencies: [self])
listen(sink.token) {[weak sink] result in
if sink?.lastResult == nil || result.isSuccess {
sink?.send(result)
}
}
return sink
}
/// Transforms a stream into a new stream. Failure results will pass through untouched.
public func map<B>(f : A -> B) -> Stream<B> {
let sink = Sink<B>(dependencies: [self])
listen(sink.token) {[weak sink] result in
sink?.send(result.map(f))
}
return sink
}
/// Transforms a stream into a new stream.
public func flatMap<B>(f : A -> Result<B>) -> Stream<B> {
let sink = Sink<B>(dependencies: [self])
listen(sink.token) {[weak sink] current in
let next = current.flatMap(f)
sink?.send(next)
}
return sink
}
/// - returns: A stream that is automatically backed by a new stream whenever the receiver fires.
public func transform<B>(f : A -> Stream<B>) -> Stream<B> {
let backed = BackedStream<B>(dependencies: [self])
listen(backed.token) {[weak backed] current in
current.ifSuccess {
backed?.backWithStream(f($0))
}
}
return backed
}
/// Stream that calls a cancelation action if the stream gets deallocated.
/// Use if you want to perform an action once no one is listening to a stream
/// for example, an expensive operation or a network request
/// - parameter cancel: The action to perform when this stream gets deallocated.
public func autoCancel(cancelAction : Removable) -> Stream<A> {
let sink = CancellingSink<A>(dependencies : [self], removable: cancelAction)
listen(sink.token) {[weak sink] current in
sink?.send(current)
}
return sink
}
/// Extends the lifetime of a stream until the first result received.
///
/// - parameter completion: A completion that fires when the stream fires
public func extendLifetimeUntilFirstResult(completion : Result<A> -> Void) {
backgroundQueue.addOperation(StreamWaitOperation(stream: self, completion: completion))
}
public func extendLifetimeUntilFirstResult(success success : A -> Void, failure : NSError -> Void) {
extendLifetimeUntilFirstResult {result in
switch result {
case let .Success(value): success(value.value)
case let .Failure(error): failure(error)
}
}
}
/// Constructs a stream that returns values from the receiver, but will return any values from *stream* until
/// the first value is sent to the receiver. For example, if you're implementing a network cache, you want to
/// return the value saved to disk, but only if the network request hasn't finished yet.
public func cachedByStream(cacheStream : Stream<A>) -> Stream<A> {
let sink = Sink<A>(dependencies: [cacheStream, self])
listen(sink.token) {[weak sink] current in
sink?.send(current)
}
cacheStream.listen(sink.token) {[weak sink, weak self] current in
if self?.lastResult == nil {
sink?.send(current)
}
}
return sink
}
}
// MARK: Writing Streams
/// A writable stream.
/// Sink is a separate type from stream to make it easy to control who can write to the stream.
/// If you need a writeble stream, typically you'll use a Sink internally,
/// but upcast to stream outside of the relevant abstraction boundary
public class Sink<A> : Stream<A> {
// This gives us an NSObject with the same lifetime as our
// sink so that we can associate a removal action for when the sink gets deallocated
private let token = NSObject()
private var open : Bool
override private init(dependencies : [StreamDependency]) {
// Streams with dependencies typically want to use their dependencies' lifetimes exclusively.
// Streams with no dependencies need to manage their own lifetime
open = dependencies.count == 0
super.init(dependencies : dependencies)
}
override private var baseActive : Bool {
return open
}
public func send(value : A) {
send(Success(value))
}
public func send(error : NSError) {
send(Failure(error))
}
public func send(result : Result<A>) {
self.lastResult = result
for listener in listeners {
listener.action?(result)
}
}
// Mark the sink as inactive. Note that closed streams with active dependencies may still be active
public func close() {
open = false
}
}
// Sink that automatically cancels an operation when it deinits.
private class CancellingSink<A> : Sink<A> {
let removable : Removable
init(dependencies : [StreamDependency], removable : Removable) {
self.removable = removable
super.init(dependencies : dependencies)
}
deinit {
removable.remove()
}
}
private class BackingRecord {
let stream : StreamDependency
let remover : Removable
init(stream : StreamDependency, remover : Removable) {
self.stream = stream
self.remover = remover
}
}
/// A stream that is rewirable. This is shorthand for the pattern of having a variable
/// representing an optional stream that is imperatively updated.
/// Using a BackedStream lets you set listeners once and always have a
/// non-optional value to pass around that others can receive values from.
public class BackedStream<A> : Stream<A> {
private var backingRecords : [BackingRecord] = []
private let token = NSObject()
override private init(dependencies : [StreamDependency]) {
super.init(dependencies : dependencies)
}
override private var baseActive : Bool {
return backingRecords.reduce(false) {$0 || $1.stream.active}
}
/// Removes the old backing and adds a new one. When the backing stream fires so will this one.
/// Think of this as rewiring a pipe from an old source to a new one.
public func backWithStream(stream : Stream<A>) -> Removable {
removeAllBackings()
return addBackingStream(stream)
}
public func addBackingStream(stream : Stream<A>) -> Removable {
let remover = stream.listen(self.token) {[weak self] result in
self?.send(result)
}
let record = BackingRecord(stream : stream, remover : remover)
self.backingRecords.append(record)
return BlockRemovable {[weak self] in
self?.removeRecord(record)
}
}
private func removeRecord(record : BackingRecord) {
record.remover.remove()
self.backingRecords = self.backingRecords.filter { $0 !== record }
}
public func removeAllBackings() {
for record in backingRecords {
record.remover.remove()
}
backingRecords = []
}
var hasBacking : Bool {
return backingRecords.count > 0
}
/// Send a new value to the stream.
func send(result : Result<A>) {
self.lastResult = result
for listener in listeners {
listener.action?(result)
}
}
}
// MARK: Combining Streams
// This is different from an option, since you can't nest nils,
// so an A?? could resolve to nil and we wouldn't be able to detect that case
private enum Resolution<A> {
case Unresolved
case Resolved(Result<A>)
}
/// Combine a pair of streams into a stream of pairs.
/// The stream will both substreams have fired.
/// After the initial load, the stream will update whenever either of the substreams updates
public func joinStreams<T, U>(t : Stream<T>, _ u: Stream<U>) -> Stream<(T, U)> {
let sink = Sink<(T, U)>(dependencies: [t, u])
let tBox = MutableBox<Resolution<T>>(.Unresolved)
let uBox = MutableBox<Resolution<U>>(.Unresolved)
t.listen(sink.token) {[weak sink] tValue in
tBox.value = .Resolved(tValue)
switch uBox.value {
case let .Resolved(uValue):
sink?.send(join(tValue, u: uValue))
case .Unresolved:
break
}
}
u.listen(sink.token) {[weak sink] uValue in
uBox.value = .Resolved(uValue)
switch tBox.value {
case let .Resolved(tValue):
sink?.send(join(tValue, u: uValue))
case .Unresolved:
break
}
}
return sink
}
/// Combine an array of streams into a stream of arrays.
/// The stream will not fire until all substreams have fired.
/// After the initial load, the stream will update whenever any of the substreams updates.
public func joinStreams<T>(streams : [Stream<T>]) -> Stream<[T]> {
// This should be unnecesary since [Stream<T>] safely upcasts to [StreamDependency]
// but in practice it causes a runtime crash as of Swift 1.2.
// Explicitly mapping it prevents the crash
let dependencies = streams.map {x -> StreamDependency in x }
let sink = Sink<[T]>(dependencies : dependencies)
let pairs = streams.map {(stream : Stream<T>) -> (box : MutableBox<Resolution<T>>, stream : Stream<T>) in
let box = MutableBox<Resolution<T>>(.Unresolved)
return (box : box, stream : stream)
}
let boxes = pairs.map { return $0.box }
for (box, stream) in pairs {
stream.listen(sink.token) {[weak sink] value in
box.value = .Resolved(value)
let results = boxes.mapOrFailIfNil {(box : MutableBox<Resolution<T>>) -> Result<T>? in
switch box.value {
case .Unresolved: return nil
case let .Resolved(v): return v
}
}
if let r = results {
sink?.send(join(r))
}
}
}
if streams.count == 0 {
sink.send(Success([]))
}
return sink
}
| apache-2.0 | 2b1dfdcf4cefb290b2945058367a63fc | 35.678643 | 209 | 0.62402 | 4.60436 | false | false | false | false |
heshamsalman/OctoViewer | OctoViewerTests/AppDelegateViewModelSpec.swift | 1 | 1587 | //
// AppDelegateViewModelSpec.swift
// OctoViewer
//
// Created by Hesham Salman on 5/26/17.
// Copyright © 2017 Hesham Salman
//
// 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 Quick
import Nimble
import Moya
@testable import OctoViewer
class AppDelegateViewModelSpec: QuickSpec {
override func spec() {
var viewModel: AppDelegateViewModelType!
var app: MockUIApplication!
beforeEach {
viewModel = AppDelegateViewModel(provider: RxMoyaProvider(stubClosure: MoyaProvider.immediatelyStub))
app = MockUIApplication()
}
describe("open url") {
var url: URL!
beforeEach {
url = URL(string: "octoviewer://auth?code=123_123_drink")
}
it("returns true") {
let expected = viewModel.inputs.application(app: app, open: url, options: [:])
expect(expected).to(beTruthy())
}
}
it("is its own input") {
expect(viewModel.inputs).to(beIdenticalTo(viewModel))
}
it("is its own output") {
expect(viewModel.outputs).to(beIdenticalTo(viewModel))
}
}
}
| apache-2.0 | fcef49fe35fae72ce4c825fb534ef614 | 26.824561 | 107 | 0.686003 | 4.087629 | false | false | false | false |
aidenluo177/Weather-Swift | Weather/Carthage/Checkouts/Alamofire/Tests/AuthenticationTests.swift | 24 | 7203 | // DownloadTests.swift
//
// Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
import Foundation
import XCTest
class AuthenticationTestCase: BaseTestCase {
// MARK: Properties
let user = "user"
let password = "password"
var URLString = ""
// MARK: Setup and Teardown
override func tearDown() {
super.tearDown()
let credentialStorage = NSURLCredentialStorage.sharedCredentialStorage()
let allCredentials = credentialStorage.allCredentials as! [NSURLProtectionSpace: AnyObject]
for (protectionSpace, credentials) in allCredentials {
if let credentials = credentials as? [String: NSURLCredential] {
for (user, credential) in credentials {
credentialStorage.removeCredential(credential, forProtectionSpace: protectionSpace)
}
}
}
}
}
// MARK: -
class BasicAuthenticationTestCase: AuthenticationTestCase {
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
self.URLString = "http://httpbin.org/basic-auth/\(user)/\(password)"
}
// MARK: Tests
func testHTTPBasicAuthenticationWithInvalidCredentials() {
// Given
let expectation = expectationWithDescription("\(self.URLString) 401")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, self.URLString)
.authenticate(user: "invalid", password: "credentials")
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? 0, -999, "error should be NSURLErrorDomain Code -999 'cancelled'")
}
func testHTTPBasicAuthenticationWithValidCredentials() {
// Given
let expectation = expectationWithDescription("\(self.URLString) 200")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, self.URLString)
.authenticate(user: self.user, password: self.password)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertEqual(response?.statusCode ?? 0, 200, "response status code should be 200")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
}
}
// MARK: -
class HTTPDigestAuthenticationTestCase: AuthenticationTestCase {
// MARK: Properties
let qop = "auth"
// MARK: Setup and Teardown
override func setUp() {
super.setUp()
self.URLString = "http://httpbin.org/digest-auth/\(qop)/\(user)/\(password)"
}
// MARK: Tests
func testHTTPDigestAuthenticationWithInvalidCredentials() {
// Given
let expectation = expectationWithDescription("\(self.URLString) 401")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, self.URLString)
.authenticate(user: "invalid", password: "credentials")
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNil(response, "response should be nil")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNotNil(error, "error should not be nil")
XCTAssertEqual(error?.code ?? 0, -999, "error should be NSURLErrorDomain Code -999 'cancelled'")
}
func testHTTPDigestAuthenticationWithValidCredentials() {
// Given
let expectation = expectationWithDescription("\(self.URLString) 200")
var request: NSURLRequest?
var response: NSHTTPURLResponse?
var data: AnyObject?
var error: NSError?
// When
Alamofire.request(.GET, self.URLString)
.authenticate(user: self.user, password: self.password)
.response { responseRequest, responseResponse, responseData, responseError in
request = responseRequest
response = responseResponse
data = responseData
error = responseError
expectation.fulfill()
}
waitForExpectationsWithTimeout(self.defaultTimeout, handler: nil)
// Then
XCTAssertNotNil(request, "request should not be nil")
XCTAssertNotNil(response, "response should not be nil")
XCTAssertEqual(response?.statusCode ?? 0, 200, "response status code should be 200")
XCTAssertNotNil(data, "data should not be nil")
XCTAssertNil(error, "error should be nil")
}
}
| mit | 517ac6ea23952b2c3133130fa6ead390 | 34.29902 | 104 | 0.652965 | 5.426526 | false | true | false | false |
harenbrs/swix | swix/swix/swix/numbers.swift | 3 | 3186 | //
// constants.swift
// swix
//
// Created by Scott Sievert on 7/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
import Accelerate
// should point to the swift folder
let S2_PREFIX = "\(NSHomeDirectory())/Developer/swix/swix/swix/swix/"
let PYTHON_PATH = "~/anaconda/bin/ipython"
// how close is close?
let S2_THRESHOLD = 1e-9
// not using let in case someone wants a variable name phi/etc
// various important constants
var pi = 3.1415926535897932384626433832795028841971693993751058
var π = pi
var tau = 2 * pi
var τ = tau
var phi = (1.0 + sqrt(5))/2
var φ = phi
var e = exp(1.double)
var euler = 0.57721566490153286060651209008240243104215933593992
// largest possible value
var inf = Double.infinity
var nan = Double.NaN
// smallest possible difference
var DOUBLE_EPSILON = DBL_EPSILON
var FLOAT_EPSILON = FLT_EPSILON
func close(x: Double, y: Double)->Bool{
return abs(x-y) < S2_THRESHOLD
}
func ~= (x:Double, y:Double)->Bool{
return close(x, y: y)
}
func rad2deg(x:Double)->Double{
return x * 180.0 / pi
}
func deg2rad(x:Double)->Double{
return x * pi / 180.0
}
func max(x:Double, y:Double)->Double{
return x < y ? y : x
}
func min(x:Double, y:Double)->Double{
return x < y ? x : y
}
func factorial(n:Double)->Double{
let y = arange(n)+1
return prod(y)
}
func binom(n:Double, k:Double)->Double{
// similar to scipy.special.binom
let i = arange(k)+1
let result = (n+1-i) / i
return prod(result)
}
// use 3.double or 3.14.int or N.int
extension Int{
var stride:vDSP_Stride {return vDSP_Stride(self)}
var length:vDSP_Length {return vDSP_Length(self)}
var int:Int {return Int(self)}
var cint:CInt {return CInt(self)}
var float:Float {return Float(self)}
var double:Double {return Double(self)}
}
extension Double{
var int:Int {return Int(self)}
var float:Float {return Float(self)}
var double:Double {return Double(self)}
var cdouble:CDouble {return CDouble(self)}
}
extension CInt{
var int:Int {return Int(self)}
var float:Float {return Float(self)}
var double:Double {return Double(self)}
}
extension Float{
var int:Int {return Int(self)}
var cfloat:CFloat {return CFloat(self)}
var float:Float {return Float(self)}
var double:Double {return Double(self)}
}
extension String {
var floatValue: Float {
return (self as NSString).floatValue
}
var doubleValue: Double {
return (self as NSString).doubleValue
}
var nsstring:NSString {return NSString(string:self)}
}
// damn integer division causes headaches
infix operator / {associativity none precedence 140}
func / (lhs: Int, rhs: Int) -> Double{
return lhs.double / rhs.double}
func / (lhs: Double, rhs: Int) -> Double{
return lhs / rhs.double}
// a quick hack to get what I want
func isNumber(x: Double) ->Bool{return true}
func isNumber(x: Float) ->Bool{return true}
func isNumber(x: Int) ->Bool{return true}
func isNumber(x: CInt) ->Bool{return true}
func isNumber(x: ndarray) ->Bool{return false}
func isNumber(x: matrix) ->Bool{return false}
func isNumber(x: AnyObject)->Bool{return false}
| mit | cee9a58069b652f8206cd503f575a46e | 23.867188 | 69 | 0.679548 | 3.198995 | false | false | false | false |
kstaring/swift | test/SILGen/expressions.swift | 1 | 16500 | // RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: echo "public var x = Int()" | %target-swift-frontend -module-name FooBar -emit-module -o %t -
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s -I%t -disable-access-control | %FileCheck %s
import Swift
import FooBar
struct SillyString : _ExpressibleByBuiltinStringLiteral, ExpressibleByStringLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) {}
init(unicodeScalarLiteral value: SillyString) { }
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
}
init(extendedGraphemeClusterLiteral value: SillyString) { }
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1) {
}
init(stringLiteral value: SillyString) { }
}
struct SillyUTF16String : _ExpressibleByBuiltinUTF16StringLiteral, ExpressibleByStringLiteral {
init(_builtinUnicodeScalarLiteral value: Builtin.Int32) { }
init(unicodeScalarLiteral value: SillyString) { }
init(
_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) {
}
init(extendedGraphemeClusterLiteral value: SillyString) { }
init(
_builtinStringLiteral start: Builtin.RawPointer,
utf8CodeUnitCount: Builtin.Word,
isASCII: Builtin.Int1
) { }
init(
_builtinUTF16StringLiteral start: Builtin.RawPointer,
utf16CodeUnitCount: Builtin.Word
) {
}
init(stringLiteral value: SillyUTF16String) { }
}
func literals() {
var a = 1
var b = 1.25
var d = "foö"
var e:SillyString = "foo"
}
// CHECK-LABEL: sil hidden @_TF11expressions8literalsFT_T_
// CHECK: integer_literal $Builtin.Int2048, 1
// CHECK: float_literal $Builtin.FPIEEE{{64|80}}, {{0x3FF4000000000000|0x3FFFA000000000000000}}
// CHECK: string_literal utf16 "foö"
// CHECK: string_literal utf8 "foo"
func bar(_ x: Int) {}
func bar(_ x: Int, _ y: Int) {}
func call_one() {
bar(42);
}
// CHECK-LABEL: sil hidden @_TF11expressions8call_oneFT_T_
// CHECK: [[BAR:%[0-9]+]] = function_ref @_TF11expressions3bar{{.*}} : $@convention(thin) (Int) -> ()
// CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42
// CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}})
// CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]])
func call_two() {
bar(42, 219)
}
// CHECK-LABEL: sil hidden @_TF11expressions8call_twoFT_T_
// CHECK: [[BAR:%[0-9]+]] = function_ref @_TF11expressions3bar{{.*}} : $@convention(thin) (Int, Int) -> ()
// CHECK: [[FORTYTWO:%[0-9]+]] = integer_literal {{.*}} 42
// CHECK: [[FORTYTWO_CONVERTED:%[0-9]+]] = apply {{.*}}([[FORTYTWO]], {{.*}})
// CHECK: [[TWONINETEEN:%[0-9]+]] = integer_literal {{.*}} 219
// CHECK: [[TWONINETEEN_CONVERTED:%[0-9]+]] = apply {{.*}}([[TWONINETEEN]], {{.*}})
// CHECK: apply [[BAR]]([[FORTYTWO_CONVERTED]], [[TWONINETEEN_CONVERTED]])
func tuples() {
bar((4, 5).1)
var T1 : (a: Int16, b: Int) = (b : 42, a : 777)
}
// CHECK-LABEL: sil hidden @_TF11expressions6tuplesFT_T_
class C {
var chi:Int
init() {
chi = 219
}
init(x:Int) {
chi = x
}
}
// CHECK-LABEL: sil hidden @_TF11expressions7classesFT_T_
func classes() {
// CHECK: function_ref @_TFC11expressions1CC{{.*}} : $@convention(method) (@thick C.Type) -> @owned C
var a = C()
// CHECK: function_ref @_TFC11expressions1CC{{.*}} : $@convention(method) (Int, @thick C.Type) -> @owned C
var b = C(x: 0)
}
struct S {
var x:Int
init() {
x = 219
}
init(x: Int) {
self.x = x
}
}
// CHECK-LABEL: sil hidden @_TF11expressions7structsFT_T_
func structs() {
// CHECK: function_ref @_TFV11expressions1SC{{.*}} : $@convention(method) (@thin S.Type) -> S
var a = S()
// CHECK: function_ref @_TFV11expressions1SC{{.*}} : $@convention(method) (Int, @thin S.Type) -> S
var b = S(x: 0)
}
func inoutcallee(_ x: inout Int) {}
func address_of_expr() {
var x: Int = 4
inoutcallee(&x)
}
func identity<T>(_ x: T) -> T {}
struct SomeStruct {
mutating
func a() {}
}
// CHECK-LABEL: sil hidden @_TF11expressions5callsFT_T_
// CHECK: [[METHOD:%[0-9]+]] = function_ref @_TFV11expressions10SomeStruct1a{{.*}} : $@convention(method) (@inout SomeStruct) -> ()
// CHECK: apply [[METHOD]]({{.*}})
func calls() {
var a : SomeStruct
a.a()
}
// CHECK-LABEL: sil hidden @_TF11expressions11module_path
func module_path() -> Int {
return FooBar.x
// CHECK: [[x_GET:%[0-9]+]] = function_ref @_TF6FooBarau1xSi
// CHECK-NEXT: apply [[x_GET]]()
}
func default_args(_ x: Int, y: Int = 219, z: Int = 20721) {}
// CHECK-LABEL: sil hidden @_TF11expressions19call_default_args_1
func call_default_args_1(_ x: Int) {
default_args(x)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF11expressions12default_args
// CHECK: [[YFUNC:%[0-9]+]] = function_ref @_TIF11expressions12default_args
// CHECK: [[Y:%[0-9]+]] = apply [[YFUNC]]()
// CHECK: [[ZFUNC:%[0-9]+]] = function_ref @_TIF11expressions12default_args
// CHECK: [[Z:%[0-9]+]] = apply [[ZFUNC]]()
// CHECK: apply [[FUNC]]({{.*}}, [[Y]], [[Z]])
}
// CHECK-LABEL: sil hidden @_TF11expressions19call_default_args_2
func call_default_args_2(_ x: Int, z: Int) {
default_args(x, z:z)
// CHECK: [[FUNC:%[0-9]+]] = function_ref @_TF11expressions12default_args
// CHECK: [[DEFFN:%[0-9]+]] = function_ref @_TIF11expressions12default_args
// CHECK-NEXT: [[C219:%[0-9]+]] = apply [[DEFFN]]()
// CHECK: apply [[FUNC]]({{.*}}, [[C219]], {{.*}})
}
struct Generic<T> {
var mono_member:Int
var typevar_member:T
// CHECK-LABEL: sil hidden @_TFV11expressions7Generic13type_variable
mutating
func type_variable() -> T.Type {
return T.self
// CHECK: [[METATYPE:%[0-9]+]] = metatype $@thick T.Type
// CHECK: return [[METATYPE]]
}
// CHECK-LABEL: sil hidden @_TFV11expressions7Generic19copy_typevar_member
mutating
func copy_typevar_member(_ x: Generic<T>) {
typevar_member = x.typevar_member
}
// CHECK-LABEL: sil hidden @_TZFV11expressions7Generic12class_method
static func class_method() {}
}
// CHECK-LABEL: sil hidden @_TF11expressions18generic_member_ref
func generic_member_ref<T>(_ x: Generic<T>) -> Int {
// CHECK: bb0([[XADDR:%[0-9]+]] : $*Generic<T>):
return x.mono_member
// CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member
// CHECK: load [trivial] [[MEMBER_ADDR]]
}
// CHECK-LABEL: sil hidden @_TF11expressions24bound_generic_member_ref
func bound_generic_member_ref(_ x: Generic<UnicodeScalar>) -> Int {
var x = x
// CHECK: bb0([[XADDR:%[0-9]+]] : $Generic<UnicodeScalar>):
return x.mono_member
// CHECK: [[MEMBER_ADDR:%[0-9]+]] = struct_element_addr {{.*}}, #Generic.mono_member
// CHECK: load [trivial] [[MEMBER_ADDR]]
}
// CHECK-LABEL: sil hidden @_TF11expressions6coerce
func coerce(_ x: Int32) -> Int64 {
return 0
}
class B {
}
class D : B {
}
// CHECK-LABEL: sil hidden @_TF11expressions8downcast
func downcast(_ x: B) -> D {
return x as! D
// CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $D
}
// CHECK-LABEL: sil hidden @_TF11expressions6upcast
func upcast(_ x: D) -> B {
return x
// CHECK: upcast %{{[0-9]+}} : ${{.*}} to $B
}
// CHECK-LABEL: sil hidden @_TF11expressions14generic_upcast
func generic_upcast<T : B>(_ x: T) -> B {
return x
// CHECK: upcast %{{.*}} to $B
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF11expressions16generic_downcast
func generic_downcast<T : B>(_ x: T, y: B) -> T {
return y as! T
// CHECK: unconditional_checked_cast %{{[0-9]+}} : {{.*}} to $T
// CHECK: return
}
// TODO: generic_downcast
// CHECK-LABEL: sil hidden @_TF11expressions15metatype_upcast
func metatype_upcast() -> B.Type {
return D.self
// CHECK: metatype $@thick D
// CHECK-NEXT: upcast
}
// CHECK-LABEL: sil hidden @_TF11expressions19interpolated_string
func interpolated_string(_ x: Int, y: String) -> String {
return "The \(x) Million Dollar \(y)"
}
protocol Runcible {
associatedtype U
var free:Int { get }
var associated:U { get }
func free_method() -> Int
mutating func associated_method() -> U.Type
static func static_method()
}
protocol Mincible {
var free:Int { get }
func free_method() -> Int
static func static_method()
}
protocol Bendable { }
protocol Wibbleable { }
// CHECK-LABEL: sil hidden @_TF11expressions20archetype_member_ref
func archetype_member_ref<T : Runcible>(_ x: T) {
var x = x
x.free_method()
// CHECK: witness_method $T, #Runcible.free_method!1
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $T
// CHECK-NEXT: copy_addr [[X:%.*]] to [initialization] [[TEMP]]
// CHECK-NEXT: apply
// CHECK-NEXT: destroy_addr [[TEMP]]
var u = x.associated_method()
// CHECK: witness_method $T, #Runcible.associated_method!1
// CHECK-NEXT: apply
T.static_method()
// CHECK: witness_method $T, #Runcible.static_method!1
// CHECK-NEXT: metatype $@thick T.Type
// CHECK-NEXT: apply
}
// CHECK-LABEL: sil hidden @_TF11expressions22existential_member_ref
func existential_member_ref(_ x: Mincible) {
x.free_method()
// CHECK: open_existential_addr
// CHECK-NEXT: witness_method
// CHECK-NEXT: apply
}
/*TODO archetype and existential properties and subscripts
func archetype_property_ref<T : Runcible>(_ x: T) -> (Int, T.U) {
x.free = x.free_method()
x.associated = x.associated_method()
return (x.free, x.associated)
}
func existential_property_ref<T : Runcible>(_ x: T) -> Int {
x.free = x.free_method()
return x.free
}
also archetype/existential subscripts
*/
struct Spoon : Runcible, Mincible {
typealias U = Float
var free: Int { return 4 }
var associated: Float { return 12 }
func free_method() -> Int {}
func associated_method() -> Float.Type {}
static func static_method() {}
}
struct Hat<T> : Runcible {
typealias U = [T]
var free: Int { return 1 }
var associated: U { get {} }
func free_method() -> Int {}
// CHECK-LABEL: sil hidden @_TFV11expressions3Hat17associated_method
mutating
func associated_method() -> U.Type {
return U.self
// CHECK: [[META:%[0-9]+]] = metatype $@thin Array<T>.Type
// CHECK: return [[META]]
}
static func static_method() {}
}
// CHECK-LABEL: sil hidden @_TF11expressions7erasure
func erasure(_ x: Spoon) -> Mincible {
return x
// CHECK: init_existential_addr
// CHECK: return
}
// CHECK-LABEL: sil hidden @_TF11expressions19declref_to_metatypeFT_MVS_5Spoon
func declref_to_metatype() -> Spoon.Type {
return Spoon.self
// CHECK: metatype $@thin Spoon.Type
}
// CHECK-LABEL: sil hidden @_TF11expressions27declref_to_generic_metatype
func declref_to_generic_metatype() -> Generic<UnicodeScalar>.Type {
// FIXME parsing of T<U> in expression context
typealias GenericChar = Generic<UnicodeScalar>
return GenericChar.self
// CHECK: metatype $@thin Generic<UnicodeScalar>.Type
}
func int(_ x: Int) {}
func float(_ x: Float) {}
func tuple() -> (Int, Float) { return (1, 1.0) }
// CHECK-LABEL: sil hidden @_TF11expressions13tuple_element
func tuple_element(_ x: (Int, Float)) {
var x = x
// CHECK: [[XADDR:%.*]] = alloc_box $@box (Int, Float)
// CHECK: [[PB:%.*]] = project_box [[XADDR]]
int(x.0)
// CHECK: tuple_element_addr [[PB]] : {{.*}}, 0
// CHECK: apply
float(x.1)
// CHECK: tuple_element_addr [[PB]] : {{.*}}, 1
// CHECK: apply
int(tuple().0)
// CHECK: [[ZERO:%.*]] = tuple_extract {{%.*}} : {{.*}}, 0
// CHECK: apply {{.*}}([[ZERO]])
float(tuple().1)
// CHECK: [[ONE:%.*]] = tuple_extract {{%.*}} : {{.*}}, 1
// CHECK: apply {{.*}}([[ONE]])
}
// CHECK-LABEL: sil hidden @_TF11expressions10containers
func containers() -> ([Int], Dictionary<String, Int>) {
return ([1, 2, 3], ["Ankeny": 1, "Burnside": 2, "Couch": 3])
}
// CHECK-LABEL: sil hidden @_TF11expressions7if_expr
func if_expr(_ a: Bool, b: Bool, x: Int, y: Int, z: Int) -> Int {
var a = a
var b = b
var x = x
var y = y
var z = z
// CHECK: bb0({{.*}}):
// CHECK: [[AB:%[0-9]+]] = alloc_box $@box Bool
// CHECK: [[PBA:%.*]] = project_box [[AB]]
// CHECK: [[BB:%[0-9]+]] = alloc_box $@box Bool
// CHECK: [[PBB:%.*]] = project_box [[BB]]
// CHECK: [[XB:%[0-9]+]] = alloc_box $@box Int
// CHECK: [[PBX:%.*]] = project_box [[XB]]
// CHECK: [[YB:%[0-9]+]] = alloc_box $@box Int
// CHECK: [[PBY:%.*]] = project_box [[YB]]
// CHECK: [[ZB:%[0-9]+]] = alloc_box $@box Int
// CHECK: [[PBZ:%.*]] = project_box [[ZB]]
return a
? x
: b
? y
: z
// CHECK: [[A:%[0-9]+]] = load [trivial] [[PBA]]
// CHECK: [[ACOND:%[0-9]+]] = apply {{.*}}([[A]])
// CHECK: cond_br [[ACOND]], [[IF_A:bb[0-9]+]], [[ELSE_A:bb[0-9]+]]
// CHECK: [[IF_A]]:
// CHECK: [[XVAL:%[0-9]+]] = load [trivial] [[PBX]]
// CHECK: br [[CONT_A:bb[0-9]+]]([[XVAL]] : $Int)
// CHECK: [[ELSE_A]]:
// CHECK: [[B:%[0-9]+]] = load [trivial] [[PBB]]
// CHECK: [[BCOND:%[0-9]+]] = apply {{.*}}([[B]])
// CHECK: cond_br [[BCOND]], [[IF_B:bb[0-9]+]], [[ELSE_B:bb[0-9]+]]
// CHECK: [[IF_B]]:
// CHECK: [[YVAL:%[0-9]+]] = load [trivial] [[PBY]]
// CHECK: br [[CONT_B:bb[0-9]+]]([[YVAL]] : $Int)
// CHECK: [[ELSE_B]]:
// CHECK: [[ZVAL:%[0-9]+]] = load [trivial] [[PBZ]]
// CHECK: br [[CONT_B:bb[0-9]+]]([[ZVAL]] : $Int)
// CHECK: [[CONT_B]]([[B_RES:%[0-9]+]] : $Int):
// CHECK: br [[CONT_A:bb[0-9]+]]([[B_RES]] : $Int)
// CHECK: [[CONT_A]]([[A_RES:%[0-9]+]] : $Int):
// CHECK: return [[A_RES]]
}
// Test that magic identifiers expand properly. We test #column here because
// it isn't affected as this testcase slides up and down the file over time.
func magic_identifier_expansion(_ a: Int = #column) {
// CHECK-LABEL: sil hidden @{{.*}}magic_identifier_expansion
// This should expand to the column number of the first _.
var tmp = #column
// CHECK: integer_literal $Builtin.Int2048, 13
// This should expand to the column number of the (, not to the column number
// of #column in the default argument list of this function.
// rdar://14315674
magic_identifier_expansion()
// CHECK: integer_literal $Builtin.Int2048, 29
}
func print_string() {
// CHECK-LABEL: print_string
var str = "\u{08}\u{09}\thello\r\n\0wörld\u{1e}\u{7f}"
// CHECK: string_literal utf16 "\u{08}\t\thello\r\n\0wörld\u{1E}\u{7F}"
}
// Test that we can silgen superclass calls that go farther than the immediate
// superclass.
class Super1 {
func funge() {}
}
class Super2 : Super1 {}
class Super3 : Super2 {
override func funge() {
super.funge()
}
}
// <rdar://problem/16880240> SILGen crash assigning to _
func testDiscardLValue() {
var a = 42
_ = a
}
func dynamicTypePlusZero(_ a : Super1) -> Super1.Type {
return type(of: a)
}
// CHECK-LABEL: dynamicTypePlusZero
// CHECK: bb0(%0 : $Super1):
// CHECK-NOT: copy_value
// CHECK: value_metatype $@thick Super1.Type, %0 : $Super1
struct NonTrivialStruct { var c : Super1 }
func dontEmitIgnoredLoadExpr(_ a : NonTrivialStruct) -> NonTrivialStruct.Type {
return type(of: a)
}
// CHECK-LABEL: dontEmitIgnoredLoadExpr
// CHECK: bb0(%0 : $NonTrivialStruct):
// CHECK-NEXT: debug_value
// CHECK-NEXT: %2 = metatype $@thin NonTrivialStruct.Type
// CHECK-NEXT: destroy_value %0
// CHECK-NEXT: return %2 : $@thin NonTrivialStruct.Type
// <rdar://problem/18851497> Swiftc fails to compile nested destructuring tuple binding
// CHECK-LABEL: sil hidden @_TF11expressions21implodeRecursiveTupleFGSqTTSiSi_Si__T_
// CHECK: bb0(%0 : $Optional<((Int, Int), Int)>):
func implodeRecursiveTuple(_ expr: ((Int, Int), Int)?) {
// CHECK: [[WHOLE:%[0-9]+]] = unchecked_enum_data {{.*}} : $Optional<((Int, Int), Int)>
// CHECK-NEXT: [[X:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 0
// CHECK-NEXT: [[X0:%[0-9]+]] = tuple_extract [[X]] : $(Int, Int), 0
// CHECK-NEXT: [[X1:%[0-9]+]] = tuple_extract [[X]] : $(Int, Int), 1
// CHECK-NEXT: [[Y:%[0-9]+]] = tuple_extract [[WHOLE]] : $((Int, Int), Int), 1
// CHECK-NEXT: [[X:%[0-9]+]] = tuple ([[X0]] : $Int, [[X1]] : $Int)
// CHECK-NEXT: debug_value [[X]] : $(Int, Int), let, name "x"
// CHECK-NEXT: debug_value [[Y]] : $Int, let, name "y"
let (x, y) = expr!
}
func test20087517() {
class Color {
static func greenColor() -> Color { return Color() }
}
let x: (Color?, Int) = (.greenColor(), 1)
}
func test20596042() {
enum E {
case thing1
case thing2
}
func f() -> (E?, Int)? {
return (.thing1, 1)
}
}
func test21886435() {
() = ()
}
| apache-2.0 | efc9cfc03814a413724a925a1a2cc388 | 27.589255 | 131 | 0.61718 | 3.175361 | false | false | false | false |
practicalswift/swift | test/stdlib/NSStringAPI.swift | 4 | 61647 | // RUN: %target-run-simple-swift
// REQUIRES: executable_test
// REQUIRES: objc_interop
// FIXME: rdar://problem/31311598
// UNSUPPORTED: OS=ios
// UNSUPPORTED: OS=tvos
// UNSUPPORTED: OS=watchos
//
// Tests for the NSString APIs as exposed by String
//
import StdlibUnittest
import Foundation
import StdlibUnittestFoundationExtras
// The most simple subclass of NSString that CoreFoundation does not know
// about.
class NonContiguousNSString : NSString {
required init(coder aDecoder: NSCoder) {
fatalError("don't call this initializer")
}
required init(itemProviderData data: Data, typeIdentifier: String) throws {
fatalError("don't call this initializer")
}
override init() {
_value = []
super.init()
}
init(_ value: [UInt16]) {
_value = value
super.init()
}
@objc(copyWithZone:) override func copy(with zone: NSZone?) -> Any {
// Ensure that copying this string produces a class that CoreFoundation
// does not know about.
return self
}
@objc override var length: Int {
return _value.count
}
@objc override func character(at index: Int) -> unichar {
return _value[index]
}
var _value: [UInt16]
}
let temporaryFileContents =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,\n" +
"sed do eiusmod tempor incididunt ut labore et dolore magna\n" +
"aliqua.\n"
func createNSStringTemporaryFile()
-> (existingPath: String, nonExistentPath: String) {
let existingPath =
createTemporaryFile("NSStringAPIs.", ".txt", temporaryFileContents)
let nonExistentPath = existingPath + "-NoNeXiStEnT"
return (existingPath, nonExistentPath)
}
var NSStringAPIs = TestSuite("NSStringAPIs")
NSStringAPIs.test("Encodings") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectNotEqual(0, availableEncodings.count)
let defaultCStringEncoding = String.defaultCStringEncoding
expectTrue(availableEncodings.contains(defaultCStringEncoding))
expectNotEqual("", String.localizedName(of: .utf8))
}
NSStringAPIs.test("NSStringEncoding") {
// Make sure NSStringEncoding and its values are type-compatible.
var enc: String.Encoding
enc = .windowsCP1250
enc = .utf32LittleEndian
enc = .utf32BigEndian
enc = .ascii
enc = .utf8
expectEqual(.utf8, enc)
}
NSStringAPIs.test("localizedStringWithFormat(_:...)") {
let world: NSString = "world"
expectEqual("Hello, world!%42", String.localizedStringWithFormat(
"Hello, %@!%%%ld", world, 42))
withOverriddenLocaleCurrentLocale("en_US") {
expectEqual("0.5", String.localizedStringWithFormat("%g", 0.5))
}
withOverriddenLocaleCurrentLocale("uk") {
expectEqual("0,5", String.localizedStringWithFormat("%g", 0.5))
}
}
NSStringAPIs.test("init(contentsOfFile:encoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
let content = try String(
contentsOfFile: existingPath, encoding: .ascii)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
do {
let _ = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectUnreachable()
} catch {
}
}
NSStringAPIs.test("init(contentsOfFile:usedEncoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
let content = try String(
contentsOfFile: existingPath, usedEncoding: &usedEncoding)
expectNotEqual(0, usedEncoding.rawValue)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
let usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
do {
_ = try String(contentsOfFile: nonExistentPath)
expectUnreachable()
} catch {
expectEqual(0, usedEncoding.rawValue)
}
}
NSStringAPIs.test("init(contentsOf:encoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
let existingURL = URL(string: "file://" + existingPath)!
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
let content = try String(
contentsOf: existingURL, encoding: .ascii)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
do {
_ = try String(contentsOf: nonExistentURL, encoding: .ascii)
expectUnreachable()
} catch {
}
}
NSStringAPIs.test("init(contentsOf:usedEncoding:error:)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
let existingURL = URL(string: "file://" + existingPath)!
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
let content = try String(
contentsOf: existingURL, usedEncoding: &usedEncoding)
expectNotEqual(0, usedEncoding.rawValue)
expectEqual(
"Lorem ipsum dolor sit amet, consectetur adipisicing elit,",
content._lines[0])
} catch {
expectUnreachableCatch(error)
}
var usedEncoding: String.Encoding = String.Encoding(rawValue: 0)
do {
_ = try String(contentsOf: nonExistentURL, usedEncoding: &usedEncoding)
expectUnreachable()
} catch {
expectEqual(0, usedEncoding.rawValue)
}
}
NSStringAPIs.test("init(cString_:encoding:)") {
expectEqual("foo, a basmati bar!",
String(cString:
"foo, a basmati bar!", encoding: String.defaultCStringEncoding))
}
NSStringAPIs.test("init(utf8String:)") {
let s = "foo あいう"
let up = UnsafeMutablePointer<UInt8>.allocate(capacity: 100)
var i = 0
for b in s.utf8 {
up[i] = b
i += 1
}
up[i] = 0
let cstr = UnsafeMutableRawPointer(up)
.bindMemory(to: CChar.self, capacity: 100)
expectEqual(s, String(utf8String: cstr))
up.deallocate()
}
NSStringAPIs.test("canBeConvertedToEncoding(_:)") {
expectTrue("foo".canBeConverted(to: .ascii))
expectFalse("あいう".canBeConverted(to: .ascii))
}
NSStringAPIs.test("capitalized") {
expectEqual("Foo Foo Foo Foo", "foo Foo fOO FOO".capitalized)
expectEqual("Жжж", "жжж".capitalized)
}
NSStringAPIs.test("localizedCapitalized") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectEqual(
"Foo Foo Foo Foo",
"foo Foo fOO FOO".localizedCapitalized)
expectEqual("Жжж", "жжж".localizedCapitalized)
return ()
}
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
withOverriddenLocaleCurrentLocale("en") {
expectEqual("Iii Iii", "iii III".localizedCapitalized)
}
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0130}ii Iıı", "iii III".localizedCapitalized)
}
}
}
/// Checks that executing the operation in the locale with the given
/// `localeID` (or if `localeID` is `nil`, the current locale) gives
/// the expected result, and that executing the operation with a nil
/// locale gives the same result as explicitly passing the system
/// locale.
///
/// - Parameter expected: the expected result when the operation is
/// executed in the given localeID
func expectLocalizedEquality(
_ expected: String,
_ op: (_: Locale?) -> String,
_ localeID: String? = nil,
_ message: @autoclosure () -> String = "",
showFrame: Bool = true,
stackTrace: SourceLocStack = SourceLocStack(),
file: String = #file, line: UInt = #line
) {
let trace = stackTrace.pushIf(showFrame, file: file, line: line)
let locale = localeID.map {
Locale(identifier: $0)
} ?? Locale.current
expectEqual(
expected, op(locale),
message(), stackTrace: trace)
}
NSStringAPIs.test("capitalizedString(with:)") {
expectLocalizedEquality(
"Foo Foo Foo Foo",
{ loc in "foo Foo fOO FOO".capitalized(with: loc) })
expectLocalizedEquality("Жжж", { loc in "жжж".capitalized(with: loc) })
expectEqual(
"Foo Foo Foo Foo",
"foo Foo fOO FOO".capitalized(with: nil))
expectEqual("Жжж", "жжж".capitalized(with: nil))
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectLocalizedEquality(
"Iii Iii",
{ loc in "iii III".capitalized(with: loc) }, "en")
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
expectLocalizedEquality(
"İii Iıı",
{ loc in "iii III".capitalized(with: loc) }, "tr")
}
NSStringAPIs.test("caseInsensitiveCompare(_:)") {
expectEqual(ComparisonResult.orderedSame,
"abCD".caseInsensitiveCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"abCD".caseInsensitiveCompare("AbCdE"))
expectEqual(ComparisonResult.orderedSame,
"абвг".caseInsensitiveCompare("АбВг"))
expectEqual(ComparisonResult.orderedAscending,
"абВГ".caseInsensitiveCompare("АбВгД"))
}
NSStringAPIs.test("commonPrefix(with:options:)") {
expectEqual("ab",
"abcd".commonPrefix(with: "abdc", options: []))
expectEqual("abC",
"abCd".commonPrefix(with: "abce", options: .caseInsensitive))
expectEqual("аб",
"абвг".commonPrefix(with: "абгв", options: []))
expectEqual("абВ",
"абВг".commonPrefix(with: "абвд", options: .caseInsensitive))
}
NSStringAPIs.test("compare(_:options:range:locale:)") {
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abc"))
expectEqual(ComparisonResult.orderedAscending,
"абв".compare("где"))
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abC", options: .caseInsensitive))
expectEqual(ComparisonResult.orderedSame,
"абв".compare("абВ", options: .caseInsensitive))
do {
let s = "abcd"
let r = s.index(after: s.startIndex)..<s.endIndex
expectEqual(ComparisonResult.orderedSame,
s.compare("bcd", range: r))
}
do {
let s = "абвг"
let r = s.index(after: s.startIndex)..<s.endIndex
expectEqual(ComparisonResult.orderedSame,
s.compare("бвг", range: r))
}
expectEqual(ComparisonResult.orderedSame,
"abc".compare("abc", locale: Locale.current))
expectEqual(ComparisonResult.orderedSame,
"абв".compare("абв", locale: Locale.current))
}
NSStringAPIs.test("completePath(into:caseSensitive:matchesInto:filterTypes)") {
let (existingPath, nonExistentPath) = createNSStringTemporaryFile()
do {
let count = nonExistentPath.completePath(caseSensitive: false)
expectEqual(0, count)
}
do {
var outputName = "None Found"
let count = nonExistentPath.completePath(
into: &outputName, caseSensitive: false)
expectEqual(0, count)
expectEqual("None Found", outputName)
}
do {
var outputName = "None Found"
var outputArray: [String] = ["foo", "bar"]
let count = nonExistentPath.completePath(
into: &outputName, caseSensitive: false, matchesInto: &outputArray)
expectEqual(0, count)
expectEqual("None Found", outputName)
expectEqual(["foo", "bar"], outputArray)
}
do {
let count = existingPath.completePath(caseSensitive: false)
expectEqual(1, count)
}
do {
var outputName = "None Found"
let count = existingPath.completePath(
into: &outputName, caseSensitive: false)
expectEqual(1, count)
expectEqual(existingPath, outputName)
}
do {
var outputName = "None Found"
var outputArray: [String] = ["foo", "bar"]
let count = existingPath.completePath(
into: &outputName, caseSensitive: false, matchesInto: &outputArray)
expectEqual(1, count)
expectEqual(existingPath, outputName)
expectEqual([existingPath], outputArray)
}
do {
var outputName = "None Found"
let count = existingPath.completePath(
into: &outputName, caseSensitive: false, filterTypes: ["txt"])
expectEqual(1, count)
expectEqual(existingPath, outputName)
}
}
NSStringAPIs.test("components(separatedBy:) (NSCharacterSet)") {
expectEqual([""], "".components(
separatedBy: CharacterSet.decimalDigits))
expectEqual(
["абв", "", "あいう", "abc"],
"абв12あいう3abc".components(
separatedBy: CharacterSet.decimalDigits))
expectEqual(
["абв", "", "あいう", "abc"],
"абв\u{1F601}\u{1F602}あいう\u{1F603}abc"
.components(
separatedBy: CharacterSet(charactersIn: "\u{1F601}\u{1F602}\u{1F603}")))
// Performs Unicode scalar comparison.
expectEqual(
["abcし\u{3099}def"],
"abcし\u{3099}def".components(
separatedBy: CharacterSet(charactersIn: "\u{3058}")))
}
NSStringAPIs.test("components(separatedBy:) (String)") {
expectEqual([""], "".components(separatedBy: "//"))
expectEqual(
["абв", "あいう", "abc"],
"абв//あいう//abc".components(separatedBy: "//"))
// Performs normalization.
expectEqual(
["abc", "def"],
"abcし\u{3099}def".components(separatedBy: "\u{3058}"))
}
NSStringAPIs.test("cString(usingEncoding:)") {
expectNil("абв".cString(using: .ascii))
let expectedBytes: [UInt8] = [ 0xd0, 0xb0, 0xd0, 0xb1, 0xd0, 0xb2, 0 ]
let expectedStr: [CChar] = expectedBytes.map { CChar(bitPattern: $0) }
expectEqual(expectedStr,
"абв".cString(using: .utf8)!)
}
NSStringAPIs.test("data(usingEncoding:allowLossyConversion:)") {
expectNil("あいう".data(using: .ascii, allowLossyConversion: false))
do {
let data = "あいう".data(using: .utf8)!
let expectedBytes: [UInt8] = [
0xe3, 0x81, 0x82, 0xe3, 0x81, 0x84, 0xe3, 0x81, 0x86
]
expectEqualSequence(expectedBytes, data)
}
}
NSStringAPIs.test("init(data:encoding:)") {
let bytes: [UInt8] = [0xe3, 0x81, 0x82, 0xe3, 0x81, 0x84, 0xe3, 0x81, 0x86]
let data = Data(bytes: bytes)
expectNil(String(data: data, encoding: .nonLossyASCII))
expectEqualSequence(
"あいう",
String(data: data, encoding: .utf8)!)
}
NSStringAPIs.test("decomposedStringWithCanonicalMapping") {
expectEqual("abc", "abc".decomposedStringWithCanonicalMapping)
expectEqual("\u{305f}\u{3099}くてん", "だくてん".decomposedStringWithCanonicalMapping)
expectEqual("\u{ff80}\u{ff9e}クテン", "ダクテン".decomposedStringWithCanonicalMapping)
}
NSStringAPIs.test("decomposedStringWithCompatibilityMapping") {
expectEqual("abc", "abc".decomposedStringWithCompatibilityMapping)
expectEqual("\u{30bf}\u{3099}クテン", "ダクテン".decomposedStringWithCompatibilityMapping)
}
NSStringAPIs.test("enumerateLines(_:)") {
var lines: [String] = []
"abc\n\ndefghi\njklm".enumerateLines {
(line: String, stop: inout Bool)
in
lines.append(line)
if lines.count == 3 {
stop = true
}
}
expectEqual(["abc", "", "defghi"], lines)
}
NSStringAPIs.test("enumerateLinguisticTagsIn(_:scheme:options:orthography:_:") {
let s: String = "Абв. Глокая куздра штеко будланула бокра и кудрячит бокрёнка. Абв."
let startIndex = s.index(s.startIndex, offsetBy: 5)
let endIndex = s.index(s.startIndex, offsetBy: 62)
var tags: [String] = []
var tokens: [String] = []
var sentences: [String] = []
let range = startIndex..<endIndex
let scheme: NSLinguisticTagScheme = .tokenType
s.enumerateLinguisticTags(in: range,
scheme: scheme.rawValue,
options: [],
orthography: nil) {
(tag: String, tokenRange: Range<String.Index>, sentenceRange: Range<String.Index>, stop: inout Bool)
in
tags.append(tag)
tokens.append(String(s[tokenRange]))
sentences.append(String(s[sentenceRange]))
if tags.count == 3 {
stop = true
}
}
expectEqual([
NSLinguisticTag.word.rawValue,
NSLinguisticTag.whitespace.rawValue,
NSLinguisticTag.word.rawValue
], tags)
expectEqual(["Глокая", " ", "куздра"], tokens)
let sentence = String(s[startIndex..<endIndex])
expectEqual([sentence, sentence, sentence], sentences)
}
NSStringAPIs.test("enumerateSubstringsIn(_:options:_:)") {
let s = "え\u{304b}\u{3099}お\u{263a}\u{fe0f}😀😊"
let startIndex = s.index(s.startIndex, offsetBy: 1)
let endIndex = s.index(s.startIndex, offsetBy: 5)
do {
var substrings: [String] = []
// FIXME(strings): this API should probably change to accept a Substring?
// instead of a String? and a range.
s.enumerateSubstrings(in: startIndex..<endIndex,
options: String.EnumerationOptions.byComposedCharacterSequences) {
(substring: String?, substringRange: Range<String.Index>,
enclosingRange: Range<String.Index>, stop: inout Bool)
in
substrings.append(substring!)
expectEqual(substring, String(s[substringRange]))
expectEqual(substring, String(s[enclosingRange]))
}
expectEqual(["\u{304b}\u{3099}", "お", "☺️", "😀"], substrings)
}
do {
var substrings: [String] = []
s.enumerateSubstrings(in: startIndex..<endIndex,
options: [.byComposedCharacterSequences, .substringNotRequired]) {
(substring_: String?, substringRange: Range<String.Index>,
enclosingRange: Range<String.Index>, stop: inout Bool)
in
expectNil(substring_)
let substring = s[substringRange]
substrings.append(String(substring))
expectEqual(substring, s[enclosingRange])
}
expectEqual(["\u{304b}\u{3099}", "お", "☺️", "😀"], substrings)
}
}
NSStringAPIs.test("fastestEncoding") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectTrue(availableEncodings.contains("abc".fastestEncoding))
}
NSStringAPIs.test("getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)") {
let s = "abc абв def где gh жз zzz"
let startIndex = s.index(s.startIndex, offsetBy: 8)
let endIndex = s.index(s.startIndex, offsetBy: 22)
do {
// 'maxLength' is limiting.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def где ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(11, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 8))
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// 'bufferLength' is limiting. Note that the buffer is not filled
// completely, since doing that would break a UTF sequence.
let bufferLength = 5
var expectedStr: [UInt8] = Array("def ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: 11, usedLength: &usedLength,
encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(4, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 4))
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// 'range' is converted completely.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def где gh жз ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: bufferLength,
usedLength: &usedLength, encoding: .utf8,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(19, usedLength)
expectEqual(remainingRange.lowerBound, endIndex)
expectEqual(remainingRange.upperBound, endIndex)
}
do {
// Inappropriate encoding.
let bufferLength = 100
var expectedStr: [UInt8] = Array("def ".utf8)
while (expectedStr.count != bufferLength) {
expectedStr.append(0xff)
}
var buffer = [UInt8](repeating: 0xff, count: bufferLength)
var usedLength = 0
var remainingRange = startIndex..<endIndex
let result = s.getBytes(&buffer, maxLength: bufferLength,
usedLength: &usedLength, encoding: .ascii,
options: [],
range: startIndex..<endIndex, remaining: &remainingRange)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
expectEqual(4, usedLength)
expectEqual(remainingRange.lowerBound, s.index(startIndex, offsetBy: 4))
expectEqual(remainingRange.upperBound, endIndex)
}
}
NSStringAPIs.test("getCString(_:maxLength:encoding:)") {
let s = "abc あかさた"
do {
// A significantly too small buffer
let bufferLength = 1
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectFalse(result)
let result2 = s.getCString(&buffer, maxLength: 1,
encoding: .utf8)
expectFalse(result2)
}
do {
// The largest buffer that cannot accommodate the string plus null terminator.
let bufferLength = 16
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectFalse(result)
let result2 = s.getCString(&buffer, maxLength: 16,
encoding: .utf8)
expectFalse(result2)
}
do {
// The smallest buffer where the result can fit.
let bufferLength = 17
var expectedStr = "abc あかさた\0".utf8.map { CChar(bitPattern: $0) }
while (expectedStr.count != bufferLength) {
expectedStr.append(CChar(bitPattern: 0xff))
}
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectTrue(result)
expectEqualSequence(expectedStr, buffer)
let result2 = s.getCString(&buffer, maxLength: 17,
encoding: .utf8)
expectTrue(result2)
expectEqualSequence(expectedStr, buffer)
}
do {
// Limit buffer size with 'maxLength'.
let bufferLength = 100
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = s.getCString(&buffer, maxLength: 8,
encoding: .utf8)
expectFalse(result)
}
do {
// String with unpaired surrogates.
let illFormedUTF16 = NonContiguousNSString([ 0xd800 ]) as String
let bufferLength = 100
var buffer = Array(
repeating: CChar(bitPattern: 0xff), count: bufferLength)
let result = illFormedUTF16.getCString(&buffer, maxLength: 100,
encoding: .utf8)
expectFalse(result)
}
}
NSStringAPIs.test("getLineStart(_:end:contentsEnd:forRange:)") {
let s = "Глокая куздра\nштеко будланула\nбокра и кудрячит\nбокрёнка."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
var outStartIndex = s.startIndex
var outLineEndIndex = s.startIndex
var outContentsEndIndex = s.startIndex
s.getLineStart(&outStartIndex, end: &outLineEndIndex,
contentsEnd: &outContentsEndIndex, for: r)
expectEqual("штеко будланула\nбокра и кудрячит\n",
s[outStartIndex..<outLineEndIndex])
expectEqual("штеко будланула\nбокра и кудрячит",
s[outStartIndex..<outContentsEndIndex])
}
}
NSStringAPIs.test("getParagraphStart(_:end:contentsEnd:forRange:)") {
let s = "Глокая куздра\nштеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n Абв."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
var outStartIndex = s.startIndex
var outEndIndex = s.startIndex
var outContentsEndIndex = s.startIndex
s.getParagraphStart(&outStartIndex, end: &outEndIndex,
contentsEnd: &outContentsEndIndex, for: r)
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n",
s[outStartIndex..<outEndIndex])
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.",
s[outStartIndex..<outContentsEndIndex])
}
}
NSStringAPIs.test("hash") {
let s: String = "abc"
let nsstr: NSString = "abc"
expectEqual(nsstr.hash, s.hash)
}
NSStringAPIs.test("init(bytes:encoding:)") {
var s: String = "abc あかさた"
expectEqual(
s, String(bytes: s.utf8, encoding: .utf8))
/*
FIXME: Test disabled because the NSString documentation is unclear about
what should actually happen in this case.
expectNil(String(bytes: bytes, length: bytes.count,
encoding: .ascii))
*/
// FIXME: add a test where this function actually returns nil.
}
NSStringAPIs.test("init(bytesNoCopy:length:encoding:freeWhenDone:)") {
var s: String = "abc あかさた"
var bytes: [UInt8] = Array(s.utf8)
expectEqual(s, String(bytesNoCopy: &bytes,
length: bytes.count, encoding: .utf8,
freeWhenDone: false))
/*
FIXME: Test disabled because the NSString documentation is unclear about
what should actually happen in this case.
expectNil(String(bytesNoCopy: &bytes, length: bytes.count,
encoding: .ascii, freeWhenDone: false))
*/
// FIXME: add a test where this function actually returns nil.
}
NSStringAPIs.test("init(utf16CodeUnits:count:)") {
let expected = "abc абв \u{0001F60A}"
let chars: [unichar] = Array(expected.utf16)
expectEqual(expected, String(utf16CodeUnits: chars, count: chars.count))
}
NSStringAPIs.test("init(utf16CodeUnitsNoCopy:count:freeWhenDone:)") {
let expected = "abc абв \u{0001F60A}"
let chars: [unichar] = Array(expected.utf16)
expectEqual(expected, String(utf16CodeUnitsNoCopy: chars,
count: chars.count, freeWhenDone: false))
}
NSStringAPIs.test("init(format:_:...)") {
expectEqual("", String(format: ""))
expectEqual(
"abc абв \u{0001F60A}", String(format: "abc абв \u{0001F60A}"))
let world: NSString = "world"
expectEqual("Hello, world!%42",
String(format: "Hello, %@!%%%ld", world, 42))
// test for rdar://problem/18317906
expectEqual("3.12", String(format: "%.2f", 3.123456789))
expectEqual("3.12", NSString(format: "%.2f", 3.123456789))
}
NSStringAPIs.test("init(format:arguments:)") {
expectEqual("", String(format: "", arguments: []))
expectEqual(
"abc абв \u{0001F60A}",
String(format: "abc абв \u{0001F60A}", arguments: []))
let world: NSString = "world"
let args: [CVarArg] = [ world, 42 ]
expectEqual("Hello, world!%42",
String(format: "Hello, %@!%%%ld", arguments: args))
}
NSStringAPIs.test("init(format:locale:_:...)") {
let world: NSString = "world"
expectEqual("Hello, world!%42", String(format: "Hello, %@!%%%ld",
locale: nil, world, 42))
}
NSStringAPIs.test("init(format:locale:arguments:)") {
let world: NSString = "world"
let args: [CVarArg] = [ world, 42 ]
expectEqual("Hello, world!%42", String(format: "Hello, %@!%%%ld",
locale: nil, arguments: args))
}
NSStringAPIs.test("utf16Count") {
expectEqual(1, "a".utf16.count)
expectEqual(2, "\u{0001F60A}".utf16.count)
}
NSStringAPIs.test("lengthOfBytesUsingEncoding(_:)") {
expectEqual(1, "a".lengthOfBytes(using: .utf8))
expectEqual(2, "あ".lengthOfBytes(using: .shiftJIS))
}
NSStringAPIs.test("lineRangeFor(_:)") {
let s = "Глокая куздра\nштеко будланула\nбокра и кудрячит\nбокрёнка."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
let result = s.lineRange(for: r)
expectEqual("штеко будланула\nбокра и кудрячит\n", s[result])
}
}
NSStringAPIs.test("linguisticTagsIn(_:scheme:options:orthography:tokenRanges:)") {
let s: String = "Абв. Глокая куздра штеко будланула бокра и кудрячит бокрёнка. Абв."
let startIndex = s.index(s.startIndex, offsetBy: 5)
let endIndex = s.index(s.startIndex, offsetBy: 17)
var tokenRanges: [Range<String.Index>] = []
let scheme = NSLinguisticTagScheme.tokenType
let tags = s.linguisticTags(in: startIndex..<endIndex,
scheme: scheme.rawValue,
options: [],
orthography: nil, tokenRanges: &tokenRanges)
expectEqual([
NSLinguisticTag.word.rawValue,
NSLinguisticTag.whitespace.rawValue,
NSLinguisticTag.word.rawValue
], tags)
expectEqual(["Глокая", " ", "куздра"],
tokenRanges.map { String(s[$0]) } )
}
NSStringAPIs.test("localizedCaseInsensitiveCompare(_:)") {
expectEqual(ComparisonResult.orderedSame,
"abCD".localizedCaseInsensitiveCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedCaseInsensitiveCompare("AbCdE"))
expectEqual(ComparisonResult.orderedSame,
"абвг".localizedCaseInsensitiveCompare("АбВг"))
expectEqual(ComparisonResult.orderedAscending,
"абВГ".localizedCaseInsensitiveCompare("АбВгД"))
}
NSStringAPIs.test("localizedCompare(_:)") {
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"абвг".localizedCompare("АбВг"))
}
NSStringAPIs.test("localizedStandardCompare(_:)") {
expectEqual(ComparisonResult.orderedAscending,
"abCD".localizedStandardCompare("AbCd"))
expectEqual(ComparisonResult.orderedAscending,
"абвг".localizedStandardCompare("АбВг"))
}
NSStringAPIs.test("localizedLowercase") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") {
expectEqual("abcd", "abCD".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("en") {
expectEqual("абвг", "абВГ".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("абвг", "абВГ".localizedLowercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("たちつてと", "たちつてと".localizedLowercase)
}
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0069}\u{0307}", "\u{0130}".localizedLowercase)
}
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0069}", "\u{0130}".localizedLowercase)
}
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
withOverriddenLocaleCurrentLocale("en") {
expectEqual(
"\u{0069}\u{0307}",
"\u{0049}\u{0307}".localizedLowercase)
}
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0069}", "\u{0049}\u{0307}".localizedLowercase)
}
}
}
NSStringAPIs.test("lowercased(with:)") {
expectLocalizedEquality("abcd", { loc in "abCD".lowercased(with: loc) }, "en")
expectLocalizedEquality("абвг", { loc in "абВГ".lowercased(with: loc) }, "en")
expectLocalizedEquality("абвг", { loc in "абВГ".lowercased(with: loc) }, "ru")
expectLocalizedEquality("たちつてと", { loc in "たちつてと".lowercased(with: loc) }, "ru")
//
// Special casing.
//
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality("\u{0069}\u{0307}", { loc in "\u{0130}".lowercased(with: loc) }, "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality("\u{0069}", { loc in "\u{0130}".lowercased(with: loc) }, "tr")
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality("\u{0069}\u{0307}", { loc in "\u{0049}\u{0307}".lowercased(with: loc) }, "en")
// U+0049 LATIN CAPITAL LETTER I
// U+0307 COMBINING DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality("\u{0069}", { loc in "\u{0049}\u{0307}".lowercased(with: loc) }, "tr")
}
NSStringAPIs.test("maximumLengthOfBytesUsingEncoding(_:)") {
do {
let s = "abc"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
do {
let s = "abc абв"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
do {
let s = "\u{1F60A}"
expectLE(s.utf8.count,
s.maximumLengthOfBytes(using: .utf8))
}
}
NSStringAPIs.test("paragraphRangeFor(_:)") {
let s = "Глокая куздра\nштеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n Абв."
let r = s.index(s.startIndex, offsetBy: 16)..<s.index(s.startIndex, offsetBy: 35)
do {
let result = s.paragraphRange(for: r)
expectEqual("штеко будланула\u{2028}бокра и кудрячит\u{2028}бокрёнка.\n", s[result])
}
}
NSStringAPIs.test("pathComponents") {
expectEqual([ "/", "foo", "bar" ] as [NSString], ("/foo/bar" as NSString).pathComponents as [NSString])
expectEqual([ "/", "абв", "где" ] as [NSString], ("/абв/где" as NSString).pathComponents as [NSString])
}
NSStringAPIs.test("precomposedStringWithCanonicalMapping") {
expectEqual("abc", "abc".precomposedStringWithCanonicalMapping)
expectEqual("だくてん",
"\u{305f}\u{3099}くてん".precomposedStringWithCanonicalMapping)
expectEqual("ダクテン",
"\u{ff80}\u{ff9e}クテン".precomposedStringWithCanonicalMapping)
expectEqual("\u{fb03}", "\u{fb03}".precomposedStringWithCanonicalMapping)
}
NSStringAPIs.test("precomposedStringWithCompatibilityMapping") {
expectEqual("abc", "abc".precomposedStringWithCompatibilityMapping)
/*
Test disabled because of:
<rdar://problem/17041347> NFKD normalization as implemented by
'precomposedStringWithCompatibilityMapping:' is not idempotent
expectEqual("\u{30c0}クテン",
"\u{ff80}\u{ff9e}クテン".precomposedStringWithCompatibilityMapping)
*/
expectEqual("ffi", "\u{fb03}".precomposedStringWithCompatibilityMapping)
}
NSStringAPIs.test("propertyList()") {
expectEqual(["foo", "bar"],
"(\"foo\", \"bar\")".propertyList() as! [String])
}
NSStringAPIs.test("propertyListFromStringsFileFormat()") {
expectEqual(["foo": "bar", "baz": "baz"],
"/* comment */\n\"foo\" = \"bar\";\n\"baz\";"
.propertyListFromStringsFileFormat() as Dictionary<String, String>)
}
NSStringAPIs.test("rangeOfCharacterFrom(_:options:range:)") {
do {
let charset = CharacterSet(charactersIn: "абв")
do {
let s = "Глокая куздра"
let r = s.rangeOfCharacter(from: charset)!
expectEqual(s.index(s.startIndex, offsetBy: 4), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 5), r.upperBound)
}
do {
expectNil("клмн".rangeOfCharacter(from: charset))
}
do {
let s = "абвклмнабвклмн"
let r = s.rangeOfCharacter(from: charset,
options: .backwards)!
expectEqual(s.index(s.startIndex, offsetBy: 9), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 10), r.upperBound)
}
do {
let s = "абвклмнабв"
let r = s.rangeOfCharacter(from: charset,
range: s.index(s.startIndex, offsetBy: 3)..<s.endIndex)!
expectEqual(s.index(s.startIndex, offsetBy: 7), r.lowerBound)
expectEqual(s.index(s.startIndex, offsetBy: 8), r.upperBound)
}
}
do {
let charset = CharacterSet(charactersIn: "\u{305f}\u{3099}")
expectNil("\u{3060}".rangeOfCharacter(from: charset))
}
do {
let charset = CharacterSet(charactersIn: "\u{3060}")
expectNil("\u{305f}\u{3099}".rangeOfCharacter(from: charset))
}
do {
let charset = CharacterSet(charactersIn: "\u{1F600}")
do {
let s = "abc\u{1F600}"
expectEqual("\u{1F600}",
s[s.rangeOfCharacter(from: charset)!])
}
do {
expectNil("abc\u{1F601}".rangeOfCharacter(from: charset))
}
}
}
NSStringAPIs.test("rangeOfComposedCharacterSequence(at:)") {
let s = "\u{1F601}abc \u{305f}\u{3099} def"
expectEqual("\u{1F601}", s[s.rangeOfComposedCharacterSequence(
at: s.startIndex)])
expectEqual("a", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 1))])
expectEqual("\u{305f}\u{3099}", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 5))])
expectEqual(" ", s[s.rangeOfComposedCharacterSequence(
at: s.index(s.startIndex, offsetBy: 6))])
}
NSStringAPIs.test("rangeOfComposedCharacterSequences(for:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("\u{1F601}a", s[s.rangeOfComposedCharacterSequences(
for: s.startIndex..<s.index(s.startIndex, offsetBy: 2))])
expectEqual("せ\u{3099}そ\u{3099}", s[s.rangeOfComposedCharacterSequences(
for: s.index(s.startIndex, offsetBy: 8)..<s.index(s.startIndex, offsetBy: 10))])
}
func toIntRange<
S : StringProtocol
>(
_ string: S, _ maybeRange: Range<String.Index>?
) -> Range<Int>? where S.Index == String.Index {
guard let range = maybeRange else { return nil }
return
string.distance(from: string.startIndex, to: range.lowerBound) ..<
string.distance(from: string.startIndex, to: range.upperBound)
}
NSStringAPIs.test("range(of:options:range:locale:)") {
do {
let s = ""
expectNil(s.range(of: ""))
expectNil(s.range(of: "abc"))
}
do {
let s = "abc"
expectNil(s.range(of: ""))
expectNil(s.range(of: "def"))
expectEqual(0..<3, toIntRange(s, s.range(of: "abc")))
}
do {
let s = "さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(2..<3, toIntRange(s, s.range(of: "す\u{3099}")))
expectEqual(2..<3, toIntRange(s, s.range(of: "\u{305a}")))
expectNil(s.range(of: "\u{3099}す"))
expectNil(s.range(of: "す"))
// Note: here `rangeOf` API produces indexes that don't point between
// grapheme cluster boundaries -- these cannot be created with public
// String interface.
//
// FIXME: why does this search succeed and the above queries fail? There is
// no apparent pattern.
expectEqual("\u{3099}", s[s.range(of: "\u{3099}")!])
}
do {
let s = "а\u{0301}б\u{0301}в\u{0301}г\u{0301}"
expectEqual(0..<1, toIntRange(s, s.range(of: "а\u{0301}")))
expectEqual(1..<2, toIntRange(s, s.range(of: "б\u{0301}")))
expectNil(s.range(of: "б"))
expectNil(s.range(of: "\u{0301}б"))
// FIXME: Again, indexes that don't correspond to grapheme
// cluster boundaries.
expectEqual("\u{0301}", s[s.range(of: "\u{0301}")!])
}
}
NSStringAPIs.test("contains(_:)") {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".contains(""))
expectFalse("".contains("a"))
expectFalse("a".contains(""))
expectFalse("a".contains("b"))
expectTrue("a".contains("a"))
expectFalse("a".contains("A"))
expectFalse("A".contains("a"))
expectFalse("a".contains("a\u{0301}"))
expectTrue("a\u{0301}".contains("a\u{0301}"))
expectFalse("a\u{0301}".contains("a"))
expectTrue("a\u{0301}".contains("\u{0301}"))
expectFalse("a".contains("\u{0301}"))
expectFalse("i".contains("I"))
expectFalse("I".contains("i"))
expectFalse("\u{0130}".contains("i"))
expectFalse("i".contains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectFalse("\u{0130}".contains("ı"))
}
}
NSStringAPIs.test("localizedCaseInsensitiveContains(_:)") {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".localizedCaseInsensitiveContains(""))
expectFalse("".localizedCaseInsensitiveContains("a"))
expectFalse("a".localizedCaseInsensitiveContains(""))
expectFalse("a".localizedCaseInsensitiveContains("b"))
expectTrue("a".localizedCaseInsensitiveContains("a"))
expectTrue("a".localizedCaseInsensitiveContains("A"))
expectTrue("A".localizedCaseInsensitiveContains("a"))
expectFalse("a".localizedCaseInsensitiveContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedCaseInsensitiveContains("a\u{0301}"))
expectFalse("a\u{0301}".localizedCaseInsensitiveContains("a"))
expectTrue("a\u{0301}".localizedCaseInsensitiveContains("\u{0301}"))
expectFalse("a".localizedCaseInsensitiveContains("\u{0301}"))
expectTrue("i".localizedCaseInsensitiveContains("I"))
expectTrue("I".localizedCaseInsensitiveContains("i"))
expectFalse("\u{0130}".localizedCaseInsensitiveContains("i"))
expectFalse("i".localizedCaseInsensitiveContains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectFalse("\u{0130}".localizedCaseInsensitiveContains("ı"))
}
}
NSStringAPIs.test("localizedStandardContains(_:)") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectFalse("".localizedStandardContains(""))
expectFalse("".localizedStandardContains("a"))
expectFalse("a".localizedStandardContains(""))
expectFalse("a".localizedStandardContains("b"))
expectTrue("a".localizedStandardContains("a"))
expectTrue("a".localizedStandardContains("A"))
expectTrue("A".localizedStandardContains("a"))
expectTrue("a".localizedStandardContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedStandardContains("a\u{0301}"))
expectTrue("a\u{0301}".localizedStandardContains("a"))
expectTrue("a\u{0301}".localizedStandardContains("\u{0301}"))
expectFalse("a".localizedStandardContains("\u{0301}"))
expectTrue("i".localizedStandardContains("I"))
expectTrue("I".localizedStandardContains("i"))
expectTrue("\u{0130}".localizedStandardContains("i"))
expectTrue("i".localizedStandardContains("\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectTrue("\u{0130}".localizedStandardContains("ı"))
}
}
}
NSStringAPIs.test("localizedStandardRange(of:)") {
if #available(OSX 10.11, iOS 9.0, *) {
func rangeOf(_ string: String, _ substring: String) -> Range<Int>? {
return toIntRange(
string, string.localizedStandardRange(of: substring))
}
withOverriddenLocaleCurrentLocale("en") { () -> Void in
expectNil(rangeOf("", ""))
expectNil(rangeOf("", "a"))
expectNil(rangeOf("a", ""))
expectNil(rangeOf("a", "b"))
expectEqual(0..<1, rangeOf("a", "a"))
expectEqual(0..<1, rangeOf("a", "A"))
expectEqual(0..<1, rangeOf("A", "a"))
expectEqual(0..<1, rangeOf("a", "a\u{0301}"))
expectEqual(0..<1, rangeOf("a\u{0301}", "a\u{0301}"))
expectEqual(0..<1, rangeOf("a\u{0301}", "a"))
do {
// FIXME: Indices that don't correspond to grapheme cluster boundaries.
let s = "a\u{0301}"
expectEqual(
"\u{0301}", s[s.localizedStandardRange(of: "\u{0301}")!])
}
expectNil(rangeOf("a", "\u{0301}"))
expectEqual(0..<1, rangeOf("i", "I"))
expectEqual(0..<1, rangeOf("I", "i"))
expectEqual(0..<1, rangeOf("\u{0130}", "i"))
expectEqual(0..<1, rangeOf("i", "\u{0130}"))
return ()
}
withOverriddenLocaleCurrentLocale("tr") {
expectEqual(0..<1, rangeOf("\u{0130}", "ı"))
}
}
}
NSStringAPIs.test("smallestEncoding") {
let availableEncodings: [String.Encoding] = String.availableStringEncodings
expectTrue(availableEncodings.contains("abc".smallestEncoding))
}
func getHomeDir() -> String {
#if os(macOS)
return String(cString: getpwuid(getuid()).pointee.pw_dir)
#elseif os(iOS) || os(tvOS) || os(watchOS)
// getpwuid() returns null in sandboxed apps under iOS simulator.
return NSHomeDirectory()
#else
preconditionFailed("implement")
#endif
}
NSStringAPIs.test("addingPercentEncoding(withAllowedCharacters:)") {
expectEqual(
"abcd1234",
"abcd1234".addingPercentEncoding(withAllowedCharacters: .alphanumerics))
expectEqual(
"abcd%20%D0%B0%D0%B1%D0%B2%D0%B3",
"abcd абвг".addingPercentEncoding(withAllowedCharacters: .alphanumerics))
}
NSStringAPIs.test("appendingFormat(_:_:...)") {
expectEqual("", "".appendingFormat(""))
expectEqual("a", "a".appendingFormat(""))
expectEqual(
"abc абв \u{0001F60A}",
"abc абв \u{0001F60A}".appendingFormat(""))
let formatArg: NSString = "привет мир \u{0001F60A}"
expectEqual(
"abc абв \u{0001F60A}def привет мир \u{0001F60A} 42",
"abc абв \u{0001F60A}"
.appendingFormat("def %@ %ld", formatArg, 42))
}
NSStringAPIs.test("appending(_:)") {
expectEqual("", "".appending(""))
expectEqual("a", "a".appending(""))
expectEqual("a", "".appending("a"))
expectEqual("さ\u{3099}", "さ".appending("\u{3099}"))
}
NSStringAPIs.test("folding(options:locale:)") {
func fwo(
_ s: String, _ options: String.CompareOptions
) -> (Locale?) -> String {
return { loc in s.folding(options: options, locale: loc) }
}
expectLocalizedEquality("abcd", fwo("abCD", .caseInsensitive), "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case:
// U+0069 LATIN SMALL LETTER I
// U+0307 COMBINING DOT ABOVE
expectLocalizedEquality(
"\u{0069}\u{0307}", fwo("\u{0130}", .caseInsensitive), "en")
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
// to lower case in Turkish locale:
// U+0069 LATIN SMALL LETTER I
expectLocalizedEquality(
"\u{0069}", fwo("\u{0130}", .caseInsensitive), "tr")
expectLocalizedEquality(
"example123", fwo("example123", .widthInsensitive), "en")
}
NSStringAPIs.test("padding(toLength:withPad:startingAtIndex:)") {
expectEqual(
"abc абв \u{0001F60A}",
"abc абв \u{0001F60A}".padding(
toLength: 10, withPad: "XYZ", startingAt: 0))
expectEqual(
"abc абв \u{0001F60A}XYZXY",
"abc абв \u{0001F60A}".padding(
toLength: 15, withPad: "XYZ", startingAt: 0))
expectEqual(
"abc абв \u{0001F60A}YZXYZ",
"abc абв \u{0001F60A}".padding(
toLength: 15, withPad: "XYZ", startingAt: 1))
}
NSStringAPIs.test("replacingCharacters(in:with:)") {
do {
let empty = ""
expectEqual("", empty.replacingCharacters(
in: empty.startIndex..<empty.startIndex, with: ""))
}
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.replacingCharacters(
in: s.startIndex..<s.startIndex, with: ""))
expectEqual(s, s.replacingCharacters(
in: s.endIndex..<s.endIndex, with: ""))
expectEqual("zzz" + s, s.replacingCharacters(
in: s.startIndex..<s.startIndex, with: "zzz"))
expectEqual(s + "zzz", s.replacingCharacters(
in: s.endIndex..<s.endIndex, with: "zzz"))
expectEqual(
"す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: ""))
expectEqual(
"zzzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: "zzz"))
expectEqual(
"\u{1F602}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.startIndex..<s.index(s.startIndex, offsetBy: 7), with: "\u{1F602}"))
expectEqual("\u{1F601}", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: ""))
expectEqual("\u{1F601}zzz", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: "zzz"))
expectEqual("\u{1F601}\u{1F602}", s.replacingCharacters(
in: s.index(after: s.startIndex)..<s.endIndex, with: "\u{1F602}"))
expectEqual(
"\u{1F601}aす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7), with: ""))
expectEqual(
"\u{1F601}azzzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7), with: "zzz"))
expectEqual(
"\u{1F601}a\u{1F602}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingCharacters(
in: s.index(s.startIndex, offsetBy: 2)..<s.index(s.startIndex, offsetBy: 7),
with: "\u{1F602}"))
}
NSStringAPIs.test("replacingOccurrences(of:with:options:range:)") {
do {
let empty = ""
expectEqual("", empty.replacingOccurrences(
of: "", with: ""))
expectEqual("", empty.replacingOccurrences(
of: "", with: "xyz"))
expectEqual("", empty.replacingOccurrences(
of: "abc", with: "xyz"))
}
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.replacingOccurrences(of: "", with: "xyz"))
expectEqual(s, s.replacingOccurrences(of: "xyz", with: ""))
expectEqual("", s.replacingOccurrences(of: s, with: ""))
expectEqual(
"\u{1F601}xyzbc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(of: "a", with: "xyz"))
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "し\u{3099}", with: "xyz"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "し\u{3099}", with: "xyz"))
expectEqual(
"\u{1F601}abc さ\u{3099}xyzす\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{3058}", with: "xyz"))
//
// Use non-default 'options:'
//
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal))
expectEqual(s, s.replacingOccurrences(
of: "\u{3058}", with: "xyz",
options: String.CompareOptions.literal))
//
// Use non-default 'range:'
//
expectEqual(
"\u{1F602}\u{1F603}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}",
s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal,
range: s.startIndex..<s.index(s.startIndex, offsetBy: 1)))
expectEqual(s, s.replacingOccurrences(
of: "\u{1F601}", with: "\u{1F602}\u{1F603}",
options: String.CompareOptions.literal,
range: s.index(s.startIndex, offsetBy: 1)..<s.index(s.startIndex, offsetBy: 3)))
}
NSStringAPIs.test("removingPercentEncoding") {
expectEqual(
"abcd абвг",
"abcd абвг".removingPercentEncoding)
expectEqual(
"abcd абвг\u{0000}\u{0001}",
"abcd абвг%00%01".removingPercentEncoding)
expectEqual(
"abcd абвг",
"%61%62%63%64%20%D0%B0%D0%B1%D0%B2%D0%B3".removingPercentEncoding)
expectEqual(
"abcd абвг",
"ab%63d %D0%B0%D0%B1%D0%B2%D0%B3".removingPercentEncoding)
expectNil("%ED%B0".removingPercentEncoding)
expectNil("%zz".removingPercentEncoding)
expectNil("abcd%FF".removingPercentEncoding)
expectNil("%".removingPercentEncoding)
}
NSStringAPIs.test("removingPercentEncoding/OSX 10.9")
.xfail(.osxMinor(10, 9, reason: "looks like a bug in Foundation in OS X 10.9"))
.xfail(.iOSMajor(7, reason: "same bug in Foundation in iOS 7.*"))
.skip(.iOSSimulatorAny("same bug in Foundation in iOS Simulator 7.*"))
.code {
expectEqual("", "".removingPercentEncoding)
}
NSStringAPIs.test("trimmingCharacters(in:)") {
expectEqual("", "".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("abc", "abc".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("", "123".trimmingCharacters(
in: CharacterSet.decimalDigits))
expectEqual("abc", "123abc789".trimmingCharacters(
in: CharacterSet.decimalDigits))
// Performs Unicode scalar comparison.
expectEqual(
"し\u{3099}abc",
"し\u{3099}abc".trimmingCharacters(
in: CharacterSet(charactersIn: "\u{3058}")))
}
NSStringAPIs.test("NSString.stringsByAppendingPaths(_:)") {
expectEqual([] as [NSString], ("" as NSString).strings(byAppendingPaths: []) as [NSString])
expectEqual(
[ "/tmp/foo", "/tmp/bar" ] as [NSString],
("/tmp" as NSString).strings(byAppendingPaths: [ "foo", "bar" ]) as [NSString])
}
NSStringAPIs.test("substring(from:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual(s, s.substring(from: s.startIndex))
expectEqual("せ\u{3099}そ\u{3099}",
s.substring(from: s.index(s.startIndex, offsetBy: 8)))
expectEqual("", s.substring(from: s.index(s.startIndex, offsetBy: 10)))
}
NSStringAPIs.test("substring(to:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("", s.substring(to: s.startIndex))
expectEqual("\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}",
s.substring(to: s.index(s.startIndex, offsetBy: 8)))
expectEqual(s, s.substring(to: s.index(s.startIndex, offsetBy: 10)))
}
NSStringAPIs.test("substring(with:)") {
let s = "\u{1F601}abc さ\u{3099}し\u{3099}す\u{3099}せ\u{3099}そ\u{3099}"
expectEqual("", s.substring(with: s.startIndex..<s.startIndex))
expectEqual(
"",
s.substring(with: s.index(s.startIndex, offsetBy: 1)..<s.index(s.startIndex, offsetBy: 1)))
expectEqual("", s.substring(with: s.endIndex..<s.endIndex))
expectEqual(s, s.substring(with: s.startIndex..<s.endIndex))
expectEqual(
"さ\u{3099}し\u{3099}す\u{3099}",
s.substring(with: s.index(s.startIndex, offsetBy: 5)..<s.index(s.startIndex, offsetBy: 8)))
}
NSStringAPIs.test("localizedUppercase") {
if #available(OSX 10.11, iOS 9.0, *) {
withOverriddenLocaleCurrentLocale("en") {
expectEqual("ABCD", "abCD".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("en") {
expectEqual("АБВГ", "абВГ".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("АБВГ", "абВГ".localizedUppercase)
}
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("たちつてと", "たちつてと".localizedUppercase)
}
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0049}", "\u{0069}".localizedUppercase)
}
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
withOverriddenLocaleCurrentLocale("tr") {
expectEqual("\u{0130}", "\u{0069}".localizedUppercase)
}
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
withOverriddenLocaleCurrentLocale("en") {
expectEqual("\u{0053}\u{0053}", "\u{00df}".localizedUppercase)
}
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
withOverriddenLocaleCurrentLocale("ru") {
expectEqual("\u{0046}\u{0049}", "\u{fb01}".localizedUppercase)
}
}
}
NSStringAPIs.test("uppercased(with:)") {
expectLocalizedEquality("ABCD", { loc in "abCD".uppercased(with: loc) }, "en")
expectLocalizedEquality("АБВГ", { loc in "абВГ".uppercased(with: loc) }, "en")
expectLocalizedEquality("АБВГ", { loc in "абВГ".uppercased(with: loc) }, "ru")
expectLocalizedEquality("たちつてと", { loc in "たちつてと".uppercased(with: loc) }, "ru")
//
// Special casing.
//
// U+0069 LATIN SMALL LETTER I
// to upper case:
// U+0049 LATIN CAPITAL LETTER I
expectLocalizedEquality("\u{0049}", { loc in "\u{0069}".uppercased(with: loc) }, "en")
// U+0069 LATIN SMALL LETTER I
// to upper case in Turkish locale:
// U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE
expectLocalizedEquality("\u{0130}", { loc in "\u{0069}".uppercased(with: loc) }, "tr")
// U+00DF LATIN SMALL LETTER SHARP S
// to upper case:
// U+0053 LATIN CAPITAL LETTER S
// U+0073 LATIN SMALL LETTER S
// But because the whole string is converted to uppercase, we just get two
// U+0053.
expectLocalizedEquality("\u{0053}\u{0053}", { loc in "\u{00df}".uppercased(with: loc) }, "en")
// U+FB01 LATIN SMALL LIGATURE FI
// to upper case:
// U+0046 LATIN CAPITAL LETTER F
// U+0069 LATIN SMALL LETTER I
// But because the whole string is converted to uppercase, we get U+0049
// LATIN CAPITAL LETTER I.
expectLocalizedEquality("\u{0046}\u{0049}", { loc in "\u{fb01}".uppercased(with: loc) }, "ru")
}
NSStringAPIs.test("write(toFile:atomically:encoding:error:)") {
let (_, nonExistentPath) = createNSStringTemporaryFile()
do {
let s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
try s.write(
toFile: nonExistentPath, atomically: false, encoding: .ascii)
let content = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectEqual(s, content)
} catch {
expectUnreachableCatch(error)
}
}
NSStringAPIs.test("write(to:atomically:encoding:error:)") {
let (_, nonExistentPath) = createNSStringTemporaryFile()
let nonExistentURL = URL(string: "file://" + nonExistentPath)!
do {
let s = "Lorem ipsum dolor sit amet, consectetur adipisicing elit"
try s.write(
to: nonExistentURL, atomically: false, encoding: .ascii)
let content = try String(
contentsOfFile: nonExistentPath, encoding: .ascii)
expectEqual(s, content)
} catch {
expectUnreachableCatch(error)
}
}
NSStringAPIs.test("applyingTransform(_:reverse:)") {
if #available(OSX 10.11, iOS 9.0, *) {
do {
let source = "tre\u{300}s k\u{fc}hl"
expectEqual(
"tres kuhl",
source.applyingTransform(.stripDiacritics, reverse: false))
}
do {
let source = "hiragana"
expectEqual(
"ひらがな",
source.applyingTransform(.latinToHiragana, reverse: false))
}
do {
let source = "ひらがな"
expectEqual(
"hiragana",
source.applyingTransform(.latinToHiragana, reverse: true))
}
}
}
NSStringAPIs.test("SameTypeComparisons") {
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
let xs = "\u{1e69}"
expectTrue(xs == "s\u{323}\u{307}")
expectFalse(xs != "s\u{323}\u{307}")
expectTrue("s\u{323}\u{307}" == xs)
expectFalse("s\u{323}\u{307}" != xs)
expectTrue("\u{1e69}" == "s\u{323}\u{307}")
expectFalse("\u{1e69}" != "s\u{323}\u{307}")
expectTrue(xs == xs)
expectFalse(xs != xs)
}
NSStringAPIs.test("MixedTypeComparisons") {
// U+0323 COMBINING DOT BELOW
// U+0307 COMBINING DOT ABOVE
// U+1E63 LATIN SMALL LETTER S WITH DOT BELOW
// NSString does not decompose characters, so the two strings will be (==) in
// swift but not in Foundation.
let xs = "\u{1e69}"
let ys: NSString = "s\u{323}\u{307}"
expectFalse(ys == "\u{1e69}")
expectTrue(ys != "\u{1e69}")
expectFalse("\u{1e69}" == ys)
expectTrue("\u{1e69}" != ys)
expectFalse(xs as NSString == ys)
expectTrue(xs as NSString != ys)
expectTrue(ys == ys)
expectFalse(ys != ys)
}
NSStringAPIs.test("CompareStringsWithUnpairedSurrogates")
.xfail(
.custom({ true },
reason: "<rdar://problem/18029104> Strings referring to underlying " +
"storage with unpaired surrogates compare unequal"))
.code {
let donor = "abcdef"
let acceptor = "\u{1f601}\u{1f602}\u{1f603}"
expectEqual("\u{fffd}\u{1f602}\u{fffd}",
acceptor[donor.index(donor.startIndex, offsetBy: 1)..<donor.index(donor.startIndex, offsetBy: 5)])
}
NSStringAPIs.test("copy construction") {
let expected = "abcd"
let x = NSString(string: expected as NSString)
expectEqual(expected, x as String)
let y = NSMutableString(string: expected as NSString)
expectEqual(expected, y as String)
}
runAllTests()
| apache-2.0 | fa36a5f815b9bee0ccfa36a47875d3e4 | 31.254019 | 105 | 0.668079 | 3.884973 | false | true | false | false |
convergeeducacao/Charts | Source/Charts/Renderers/BarChartRenderer.swift | 4 | 22885 | //
// BarChartRenderer.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
open class BarChartRenderer: BarLineScatterCandleBubbleRenderer
{
fileprivate class Buffer
{
var rects = [CGRect]()
}
open weak var dataProvider: BarChartDataProvider?
public init(dataProvider: BarChartDataProvider?, animator: Animator?, viewPortHandler: ViewPortHandler?)
{
super.init(animator: animator, viewPortHandler: viewPortHandler)
self.dataProvider = dataProvider
}
// [CGRect] per dataset
fileprivate var _buffers = [Buffer]()
open override func initBuffers()
{
if let barData = dataProvider?.barData
{
// Matche buffers count to dataset count
if _buffers.count != barData.dataSetCount
{
while _buffers.count < barData.dataSetCount
{
_buffers.append(Buffer())
}
while _buffers.count > barData.dataSetCount
{
_buffers.removeLast()
}
}
for i in stride(from: 0, to: barData.dataSetCount, by: 1)
{
let set = barData.dataSets[i] as! IBarChartDataSet
let size = set.entryCount * (set.isStacked ? set.stackSize : 1)
if _buffers[i].rects.count != size
{
_buffers[i].rects = [CGRect](repeating: CGRect(), count: size)
}
}
}
else
{
_buffers.removeAll()
}
}
fileprivate func prepareBuffer(dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData,
let animator = animator
else { return }
let barWidthHalf = barData.barWidth / 2.0
let buffer = _buffers[index]
var bufferIndex = 0
let containsStacks = dataSet.isStacked
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
let phaseY = animator.phaseY
var barRect = CGRect()
var x: Double
var y: Double
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
let vals = e.yValues
x = e.x
y = e.y
if !containsStacks || vals == nil
{
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= 0.0 ? CGFloat(y) : 0)
: (y >= 0.0 ? CGFloat(y) : 0)
var bottom = isInverted
? (y >= 0.0 ? CGFloat(y) : 0)
: (y <= 0.0 ? CGFloat(y) : 0)
// multiply the height of the rect with the phase
if top > 0
{
top *= CGFloat(phaseY)
}
else
{
bottom *= CGFloat(phaseY)
}
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
else
{
var posY = 0.0
var negY = -e.negativeSum
var yStart = 0.0
// fill the stack
for k in 0 ..< vals!.count
{
let value = vals![k]
if value >= 0.0
{
y = posY
yStart = posY + value
posY = yStart
}
else
{
y = negY
yStart = negY + abs(value)
negY += abs(value)
}
let left = CGFloat(x - barWidthHalf)
let right = CGFloat(x + barWidthHalf)
var top = isInverted
? (y <= yStart ? CGFloat(y) : CGFloat(yStart))
: (y >= yStart ? CGFloat(y) : CGFloat(yStart))
var bottom = isInverted
? (y >= yStart ? CGFloat(y) : CGFloat(yStart))
: (y <= yStart ? CGFloat(y) : CGFloat(yStart))
// multiply the height of the rect with the phase
top *= CGFloat(phaseY)
bottom *= CGFloat(phaseY)
barRect.origin.x = left
barRect.size.width = right - left
barRect.origin.y = top
barRect.size.height = bottom - top
buffer.rects[bufferIndex] = barRect
bufferIndex += 1
}
}
}
}
open override func drawData(context: CGContext)
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
for i in 0 ..< barData.dataSetCount
{
guard let set = barData.getDataSetByIndex(i) else { continue }
if set.isVisible
{
if !(set is IBarChartDataSet)
{
fatalError("Datasets for BarChartRenderer must conform to IBarChartDataset")
}
drawDataSet(context: context, dataSet: set as! IBarChartDataSet, index: i)
}
}
}
fileprivate var _barShadowRectBuffer: CGRect = CGRect()
open func drawDataSet(context: CGContext, dataSet: IBarChartDataSet, index: Int)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler
else { return }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
prepareBuffer(dataSet: dataSet, index: index)
trans.rectValuesToPixel(&_buffers[index].rects)
let borderWidth = dataSet.barBorderWidth
let borderColor = dataSet.barBorderColor
let drawBorder = borderWidth > 0.0
context.saveGState()
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
guard
let animator = animator,
let barData = dataProvider.barData
else { return }
let barWidth = barData.barWidth
let barWidthHalf = barWidth / 2.0
var x: Double = 0.0
for i in stride(from: 0, to: min(Int(ceil(Double(dataSet.entryCount) * animator.phaseX)), dataSet.entryCount), by: 1)
{
guard let e = dataSet.entryForIndex(i) as? BarChartDataEntry else { continue }
x = e.x
_barShadowRectBuffer.origin.x = CGFloat(x - barWidthHalf)
_barShadowRectBuffer.size.width = CGFloat(barWidth)
trans.rectValueToPixel(&_barShadowRectBuffer)
if !viewPortHandler.isInBoundsLeft(_barShadowRectBuffer.origin.x + _barShadowRectBuffer.size.width)
{
continue
}
if !viewPortHandler.isInBoundsRight(_barShadowRectBuffer.origin.x)
{
break
}
_barShadowRectBuffer.origin.y = viewPortHandler.contentTop
_barShadowRectBuffer.size.height = viewPortHandler.contentHeight
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(_barShadowRectBuffer)
}
}
let buffer = _buffers[index]
// draw the bar shadow before the values
if dataProvider.isDrawBarShadowEnabled
{
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
context.setFillColor(dataSet.barShadowColor.cgColor)
context.fill(barRect)
}
}
let isSingleColor = dataSet.colors.count == 1
if isSingleColor
{
context.setFillColor(dataSet.color(atIndex: 0).cgColor)
}
for j in stride(from: 0, to: buffer.rects.count, by: 1)
{
let barRect = buffer.rects[j]
if (!viewPortHandler.isInBoundsLeft(barRect.origin.x + barRect.size.width))
{
continue
}
if (!viewPortHandler.isInBoundsRight(barRect.origin.x))
{
break
}
if !isSingleColor
{
// Set the color for the currently drawn value. If the index is out of bounds, reuse colors.
context.setFillColor(dataSet.color(atIndex: j).cgColor)
}
context.fill(barRect)
if drawBorder
{
context.setStrokeColor(borderColor.cgColor)
context.setLineWidth(borderWidth)
context.stroke(barRect)
}
}
context.restoreGState()
}
open func prepareBarHighlight(
x: Double,
y1: Double,
y2: Double,
barWidthHalf: Double,
trans: Transformer,
rect: inout CGRect)
{
let left = x - barWidthHalf
let right = x + barWidthHalf
let top = y1
let bottom = y2
rect.origin.x = CGFloat(left)
rect.origin.y = CGFloat(top)
rect.size.width = CGFloat(right - left)
rect.size.height = CGFloat(bottom - top)
trans.rectValueToPixel(&rect, phaseY: animator?.phaseY ?? 1.0)
}
open override func drawValues(context: CGContext)
{
// if values are drawn
if isDrawingValuesAllowed(dataProvider: dataProvider)
{
guard
let dataProvider = dataProvider,
let viewPortHandler = self.viewPortHandler,
let barData = dataProvider.barData,
let animator = animator
else { return }
var dataSets = barData.dataSets
let valueOffsetPlus: CGFloat = 4.5
var posOffset: CGFloat
var negOffset: CGFloat
let drawValueAboveBar = dataProvider.isDrawValueAboveBarEnabled
for dataSetIndex in 0 ..< barData.dataSetCount
{
guard let dataSet = dataSets[dataSetIndex] as? IBarChartDataSet else { continue }
if !shouldDrawValues(forDataSet: dataSet)
{
continue
}
let isInverted = dataProvider.isInverted(axis: dataSet.axisDependency)
// calculate the correct offset depending on the draw position of the value
let valueFont = dataSet.valueFont
let valueTextHeight = valueFont.lineHeight
posOffset = (drawValueAboveBar ? -(valueTextHeight + valueOffsetPlus) : valueOffsetPlus)
negOffset = (drawValueAboveBar ? valueOffsetPlus : -(valueTextHeight + valueOffsetPlus))
if isInverted
{
posOffset = -posOffset - valueTextHeight
negOffset = -negOffset - valueTextHeight
}
let buffer = _buffers[dataSetIndex]
guard let formatter = dataSet.valueFormatter else { continue }
let trans = dataProvider.getTransformer(forAxis: dataSet.axisDependency)
let phaseY = animator.phaseY
// if only single values are drawn (sum)
if !dataSet.isStacked
{
for j in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(j) as? BarChartDataEntry else { continue }
let rect = buffer.rects[j]
let x = rect.origin.x + rect.size.width / 2.0
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
let val = e.y
drawValue(
context: context,
value: formatter.stringForValue(
val,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: val >= 0.0
? (rect.origin.y + posOffset)
: (rect.origin.y + rect.size.height + negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(j))
}
}
else
{
// if we have stacks
var bufferIndex = 0
for index in 0 ..< Int(ceil(Double(dataSet.entryCount) * animator.phaseX))
{
guard let e = dataSet.entryForIndex(index) as? BarChartDataEntry else { continue }
let vals = e.yValues
let rect = buffer.rects[bufferIndex]
let x = rect.origin.x + rect.size.width / 2.0
// we still draw stacked bars, but there is one non-stacked in between
if vals == nil
{
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(rect.origin.y)
|| !viewPortHandler.isInBoundsLeft(x)
{
continue
}
drawValue(
context: context,
value: formatter.stringForValue(
e.y,
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: rect.origin.y +
(e.y >= 0 ? posOffset : negOffset),
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
else
{
// draw stack values
let vals = vals!
var transformed = [CGPoint]()
var posY = 0.0
var negY = -e.negativeSum
for k in 0 ..< vals.count
{
let value = vals[k]
var y: Double
if value >= 0.0
{
posY += value
y = posY
}
else
{
y = negY
negY -= value
}
transformed.append(CGPoint(x: 0.0, y: CGFloat(y * phaseY)))
}
trans.pointValuesToPixel(&transformed)
for k in 0 ..< transformed.count
{
let y = transformed[k].y + (vals[k] >= 0 ? posOffset : negOffset)
if !viewPortHandler.isInBoundsRight(x)
{
break
}
if !viewPortHandler.isInBoundsY(y) || !viewPortHandler.isInBoundsLeft(x)
{
continue
}
drawValue(
context: context,
value: formatter.stringForValue(
vals[k],
entry: e,
dataSetIndex: dataSetIndex,
viewPortHandler: viewPortHandler),
xPos: x,
yPos: y,
font: valueFont,
align: .center,
color: dataSet.valueTextColorAt(index))
}
}
bufferIndex = vals == nil ? (bufferIndex + 1) : (bufferIndex + vals!.count)
}
}
}
}
}
/// Draws a value at the specified x and y position.
open func drawValue(context: CGContext, value: String, xPos: CGFloat, yPos: CGFloat, font: NSUIFont, align: NSTextAlignment, color: NSUIColor)
{
ChartUtils.drawText(context: context, text: value, point: CGPoint(x: xPos, y: yPos), align: align, attributes: [NSFontAttributeName: font, NSForegroundColorAttributeName: color])
}
open override func drawExtras(context: CGContext)
{
}
open override func drawHighlighted(context: CGContext, indices: [Highlight])
{
guard
let dataProvider = dataProvider,
let barData = dataProvider.barData
else { return }
context.saveGState()
var barRect = CGRect()
for high in indices
{
guard
let set = barData.getDataSetByIndex(high.dataSetIndex) as? IBarChartDataSet,
set.isHighlightEnabled
else { continue }
if let e = set.entryForXValue(high.x) as? BarChartDataEntry
{
if !isInBoundsX(entry: e, dataSet: set)
{
continue
}
let trans = dataProvider.getTransformer(forAxis: set.axisDependency)
context.setFillColor(set.highlightColor.cgColor)
context.setAlpha(set.highlightAlpha)
let isStack = high.stackIndex >= 0 && e.isStacked
let y1: Double
let y2: Double
if isStack
{
if dataProvider.isHighlightFullBarEnabled
{
y1 = e.positiveSum
y2 = -e.negativeSum
}
else
{
let range = e.ranges?[high.stackIndex]
y1 = range?.from ?? 0.0
y2 = range?.to ?? 0.0
}
}
else
{
y1 = e.y
y2 = 0.0
}
prepareBarHighlight(x: e.x, y1: y1, y2: y2, barWidthHalf: barData.barWidth / 2.0, trans: trans, rect: &barRect)
setHighlightDrawPos(highlight: high, barRect: barRect)
context.fill(barRect)
}
}
context.restoreGState()
}
/// Sets the drawing position of the highlight object based on the riven bar-rect.
internal func setHighlightDrawPos(highlight high: Highlight, barRect: CGRect)
{
high.setDraw(x: barRect.midX, y: barRect.origin.y)
}
}
| apache-2.0 | 05b2ac02c0c18dc4e956f49dac148aa1 | 35.210443 | 186 | 0.417391 | 6.519943 | false | false | false | false |
lieonCX/Live | Live/Model/Home/LiveListModel.swift | 1 | 2304 | //
// LiveListModel.swift
// Live
//
// Created by lieon on 2017/7/6.
// Copyright © 2017年 ChengDuHuanLeHui. All rights reserved.
//
import Foundation
import ObjectMapper
import RxDataSources
import Kingfisher
class ListGroup: Model {
var group: [LiveListModel]?
override func mapping(map: Map) {
group <- map["list"]
}
}
class LiveListModel: Model {
var liveId: Int?
var name: String?
var cover: String? {
didSet {
guard let imageURL = URL(string: CustomKey.URLKey.baseImageUrl + (cover ?? "")) else { return }
ImageDownloader.default.downloadImage(with: imageURL, retrieveImageTask: nil, options: nil, progressBlock: nil) { (image, _, _, _) in
self.coverImage = image
}
}
}
var city: String?
var level: Int = 0
var userName: String?
var avatar: String?
var userId: Int = 0
var seeCount: Int = 0
var type: ListLiveType = .none
var playUrlRtmp: String?
var playUrlFlv: String?
var playUrlHls: String?
var longitude: Double = 0.0
var latitude: Double = 0.0
var distance: UInt = 0
var replayUrlMp4: String?
var replayUrlFlv: String?
var replayUrlHls: String?
var startTime: Int = 0
var endTime: Int = 0
var groupId: String?
var isFollow: Bool = false
var seeingCount: Int = 0
var coverImage: UIImage?
override func mapping(map: Map) {
liveId <- map["id"]
name <- map["name"]
cover <- map["cover"]
city <- map["city"]
level <- map["level"]
userName <- map["userName"]
avatar <- map["avastar"]
userId <- map["userId"]
seeCount <- map["seeCount"]
type <- map["type"]
playUrlRtmp <- map["playUrlRtmp"]
playUrlFlv <- map["playUrlFlv"]
playUrlHls <- map["playUrlHls"]
longitude <- map["lng"]
latitude <- map["lat"]
distance <- map["distance"]
replayUrlMp4 <- map["replayUrlMp4"]
replayUrlFlv <- map["replayUrlFlv"]
replayUrlHls <- map["replayUrlHls"]
startTime <- map["startTime"]
endTime <- map["endTime"]
groupId <- map["groupId"]
isFollow <- map["isFollow"]
seeingCount <- map["seeingCount"]
}
}
| mit | af2e1e0c5d38b96fa040e1064a3bb455 | 27.060976 | 145 | 0.583225 | 3.974093 | false | false | false | false |
arsonik/AKTransmission | Source/Transmission.swift | 1 | 6502 | //
// Transmission.swift
//
// Created by Florian Morello on 30/07/14.
// Copyright (c) 2014 Arsonik. All rights reserved.
//
import Foundation
import Alamofire
open class Transmission {
fileprivate let sessionHeader: String = "X-Transmission-Session-Id"
fileprivate var sessionId: String!
open let username: String
open let password: String
open let host: String
open let port: UInt
open var timeout: TimeInterval = 5
public typealias completionHandler = (Any?, Error?) -> Void
public init(host: String, username: String, password: String, port: UInt! = 9091) {
self.username = username
self.password = password
self.host = host
self.port = port
}
fileprivate func request(_ route: TransmissionRoute) -> URLRequest {
var request = route.urlRequest
request.httpMethod = "POST"
var comps = URLComponents(url: request.url!, resolvingAgainstBaseURL: false)!
comps.host = host
comps.port = Int(port)
request.url = comps.url!
request.setValue(sessionId, forHTTPHeaderField: sessionHeader)
request.timeoutInterval = timeout
return request
}
private enum ResponseStatus {
case retry
case success([String: AnyObject])
case error(Error?)
}
private func handleResponse(_ response: DataResponse<Any>) -> ResponseStatus {
if let sid = response.response?.allHeaderFields[self.sessionHeader] as? String,
response.response?.statusCode == 409 {
self.sessionId = sid
return ResponseStatus.retry
} else if let res = response.result.value as? [String: AnyObject],
let result = res["result"] as? String,
let args = res["arguments"] as? [String: AnyObject],
result == "success" {
return .success(args)
} else {
print("ERROR")
dump(response.result)
return ResponseStatus.error(response.result.error)
}
}
open func loadMagnetLink(_ magnet: String,
success: @escaping ((_ success: Bool, _ error: Error?) -> Void)) -> Request {
let route = TransmissionRoute.magnetLink(magnet)
return Alamofire.request(request(route))
.authenticate(user: username, password: password)
.responseJSON { [weak self] response in
guard let handled = self?.handleResponse(response) else {
return
}
switch handled {
case .retry:
let _ = self?.loadMagnetLink(magnet, success: success)
case .success:
success(true, nil)
case .error(let error):
success(false, error)
}
}
}
open func sessionGet(_ completion: @escaping (TransmissionSession?, Error?) -> Void) -> Request {
return Alamofire.request(request(TransmissionRoute.sessionGet))
.authenticate(user: username, password: password)
.responseJSON { [weak self] response in
guard let handled = self?.handleResponse(response) else {
return
}
switch handled {
case .retry:
let _ = self?.sessionGet(completion)
case .success(let data):
completion(TransmissionSession(data: data), nil)
case .error(let error):
completion(nil, error)
}
}
}
open func sessionSet(_ arguments: [String: Any], completion: @escaping completionHandler) -> Request {
return Alamofire.request(request(TransmissionRoute.sessionSet(arguments)))
.authenticate(user: username, password: password)
.responseJSON { [weak self] response in
guard let handled = self?.handleResponse(response) else {
return
}
switch handled {
case .retry:
let _ = self?.sessionSet(arguments, completion: completion)
case .success(let data):
completion(data, nil)
case .error(let error):
completion(nil, error)
}
}
}
open func pauseTorrent(_ torrents: [TransmissionTorrent],
completion: @escaping completionHandler) -> Request {
let ids = torrents.flatMap {
$0.id
}
return Alamofire.request(request(TransmissionRoute.torrentStop(ids)))
.authenticate(user: username, password: password)
.responseJSON { [weak self] response in
guard let handled = self?.handleResponse(response) else {
return
}
switch handled {
case .retry:
let _ = self?.pauseTorrent(torrents, completion: completion)
case .success:
completion(true, nil)
case .error(let error):
completion(nil, error)
}
}
}
open func resumeTorrent(_ torrents: [TransmissionTorrent], completion: @escaping completionHandler) -> Request {
let ids = torrents.flatMap {
$0.id
}
return Alamofire.request(request(TransmissionRoute.torrentStart(ids)))
.authenticate(user: username, password: password)
.responseJSON { [weak self] response in
guard let handled = self?.handleResponse(response) else {
return
}
switch handled {
case .retry:
let _ = self?.resumeTorrent(torrents, completion: completion)
case .success:
completion(true, nil)
case .error(let error):
completion(nil, error)
}
}
}
open func removeTorrent(_ torrents: [TransmissionTorrent],
trashData: Bool,
completion: @escaping completionHandler) -> Request {
let ids = torrents.flatMap {
$0.id
}
return Alamofire.request(request(TransmissionRoute.torrentRemove(ids: ids, trashData: trashData)))
.authenticate(user: username, password: password)
.responseJSON { [weak self] response in
guard let handled = self?.handleResponse(response) else {
return
}
switch handled {
case .retry:
let _ = self?.removeTorrent(torrents, trashData: trashData, completion: completion)
case .success:
completion(true, nil)
case .error(let error):
completion(nil, error)
}
}
}
open func torrentGet(_ completion: @escaping ([TransmissionTorrent]?, Error?) -> Void) -> Request {
return Alamofire.request(request(TransmissionRoute.torrentGet))
.authenticate(user: username, password: password)
.responseJSON { [weak self] response in
guard let handled = self?.handleResponse(response) else {
return
}
switch handled {
case .retry:
let _ = self?.torrentGet(completion)
case .success(let data):
if let torrents = data["torrents"] as? [[String: AnyObject]] {
completion(torrents.flatMap({
TransmissionTorrent(data: $0)
}), nil)
} else {
completion(nil, NSError(domain: "cannot find any torrents", code: 404, userInfo: nil))
}
case .error(let error):
completion(nil, error)
}
}
}
}
| mit | 4aeb641180bceb5c6215cd907a003585 | 29.669811 | 113 | 0.665026 | 3.835988 | false | false | false | false |
YR/Cachyr | Tests/CachyrTests/MemoryCacheTests.swift | 1 | 12342 | /**
* Cachyr
*
* Copyright (c) 2016 NRK. Licensed under the MIT license, as follows:
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import XCTest
@testable import Cachyr
class MemoryCacheTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testIntValues() {
let cache = MemoryCache<Int>()
cache.setValue(42, forKey: "Int")
let intValue = cache.value(forKey: "Int")
XCTAssertNotNil(intValue)
XCTAssertEqual(42, intValue!)
}
func testDoubleValues() {
let cache = MemoryCache<Double>()
cache.setValue(42.0, forKey: "Double")
let doubleValue = cache.value(forKey: "Double")
XCTAssertNotNil(doubleValue)
XCTAssertEqual(42.0, doubleValue!)
}
func testStringValues() {
let cache = MemoryCache<String>()
cache.setValue("Test", forKey: "String")
let stringValue = cache.value(forKey: "String")
XCTAssertNotNil(stringValue)
XCTAssertEqual("Test", stringValue!)
}
func testStructValues() {
struct Foo {
let bar = "Bar"
}
let cache = MemoryCache<Foo>()
cache.setValue(Foo(), forKey: "Foo")
let foo = cache.value(forKey: "Foo")
XCTAssertNotNil(foo)
XCTAssertEqual("Bar", foo!.bar)
}
func testClassValues() {
class Foo {
let bar = "Bar"
}
let cache = MemoryCache<Foo>()
cache.setValue(Foo(), forKey: "Foo")
let foo = cache.value(forKey: "Foo")
XCTAssertNotNil(foo)
XCTAssertEqual("Bar", foo!.bar)
}
func testContains() {
let cache = MemoryCache<String>()
let key = "foo"
XCTAssertFalse(cache.contains(key: key))
cache.setValue(key, forKey: key)
XCTAssertTrue(cache.contains(key: key))
}
func testRemove() {
let cache = MemoryCache<String>()
let key = "foo"
cache.setValue(key, forKey: key)
var value = cache.value(forKey: key)
XCTAssertNotNil(value)
cache.removeValue(forKey: key)
value = cache.value(forKey: key)
XCTAssertNil(value)
}
func testRemoveAll() {
let cache = MemoryCache<Int>()
let values = [1, 2, 3]
for i in values {
cache.setValue(i, forKey: "\(i)")
}
for i in values {
let value = cache.value(forKey: "\(i)")
XCTAssertNotNil(value)
XCTAssertEqual(value!, i)
}
cache.removeAll()
for i in values {
let value = cache.value(forKey: "\(i)")
XCTAssertNil(value)
}
}
func testExpiration() {
let cache = MemoryCache<String>()
let foo = "foo"
let hasNotExpiredDate = Date(timeIntervalSinceNow: 30)
cache.setValue(foo, forKey: foo, expires: hasNotExpiredDate)
let notExpiredValue = cache.value(forKey: foo)
XCTAssertNotNil(notExpiredValue)
let hasExpiredDate = Date(timeIntervalSinceNow: -30)
cache.setValue(foo, forKey: foo, expires: hasExpiredDate)
let expiredValue = cache.value(forKey: foo)
XCTAssertNil(expiredValue)
}
func testRemoveExpired() {
let cache = MemoryCache<String>()
let foo = "foo"
let bar = "bar"
let barExpireDate = Date(timeIntervalSinceNow: -30)
cache.setValue(foo, forKey: foo)
cache.setValue(bar, forKey: bar, expires: barExpireDate)
cache.removeExpired()
let fooValue = cache.value(forKey: foo)
XCTAssertNotNil(fooValue)
let barValue = cache.value(forKey: bar)
XCTAssertNil(barValue)
}
func testExpirationInterval() {
let cache = MemoryCache<String>()
let foo = "foo"
cache.setValue(foo, forKey: foo, expires: Date())
cache.checkExpiredInterval = 0
let fooValue = cache.value(forKey: foo)
XCTAssertNil(fooValue)
}
func testSetGetExpiration() {
let cache = MemoryCache<String>()
let expires = Date().addingTimeInterval(10)
let foo = "foo"
cache.setValue(foo, forKey: foo)
let noExpire = cache.expirationDate(forKey: foo)
XCTAssertNil(noExpire)
cache.setExpirationDate(expires, forKey: foo)
let expire = cache.expirationDate(forKey: foo)
XCTAssertNotNil(expire)
XCTAssertEqual(expires, expire)
}
func testRemoveExpiration() {
let cache = MemoryCache<String>()
let expiration = Date().addingTimeInterval(10)
let foo = "foo"
cache.setValue(foo, forKey: foo)
let noExpire = cache.expirationDate(forKey: foo)
XCTAssertNil(noExpire)
cache.setExpirationDate(expiration, forKey: foo)
let expire = cache.expirationDate(forKey: foo)
XCTAssertNotNil(expire)
cache.setExpirationDate(nil, forKey: foo)
let expirationGone = cache.expirationDate(forKey: foo)
XCTAssertNil(expirationGone)
}
func testRemoveItemsOlderThan() {
let cache = MemoryCache<String>()
let foo = "foo"
cache.setValue(foo, forKey: foo)
cache.removeItems(olderThan: Date(timeIntervalSinceNow: -30))
XCTAssertNotNil(cache.value(forKey: foo))
cache.removeItems(olderThan: Date())
XCTAssertNil(cache.value(forKey: foo))
}
func testInteger() {
let cacheInt = MemoryCache<Int>()
let int = Int(Int.min)
cacheInt.setValue(int, forKey: "Int")
let intValue = cacheInt.value(forKey: "Int")
XCTAssertNotNil(intValue)
XCTAssertEqual(intValue!, int)
let cacheInt8 = MemoryCache<Int8>()
let int8 = Int8(Int8.min)
cacheInt8.setValue(int8, forKey: "Int8")
let int8Value = cacheInt8.value(forKey: "Int8")
XCTAssertNotNil(int8Value)
XCTAssertEqual(int8Value!, int8)
let cacheInt16 = MemoryCache<Int16>()
let int16 = Int16(Int16.min)
cacheInt16.setValue(int16, forKey: "Int16")
let int16Value = cacheInt16.value(forKey: "Int16")
XCTAssertNotNil(int16Value)
XCTAssertEqual(int16Value!, int16)
let cacheInt32 = MemoryCache<Int32>()
let int32 = Int32(Int32.min)
cacheInt32.setValue(int32, forKey: "Int32")
let int32Value = cacheInt32.value(forKey: "Int32")
XCTAssertNotNil(int32Value)
XCTAssertEqual(int32Value!, int32)
let cacheInt64 = MemoryCache<Int64>()
let int64 = Int64(Int64.min)
cacheInt64.setValue(int64, forKey: "Int64")
let int64Value = cacheInt64.value(forKey: "Int64")
XCTAssertNotNil(int64Value)
XCTAssertEqual(int64Value!, int64)
let cacheUInt = MemoryCache<UInt>()
let uint = UInt(UInt.max)
cacheUInt.setValue(uint, forKey: "UInt")
let uintValue = cacheUInt.value(forKey: "UInt")
XCTAssertNotNil(uintValue)
XCTAssertEqual(uintValue!, uint)
let cacheUInt8 = MemoryCache<UInt8>()
let uint8 = UInt8(UInt8.max)
cacheUInt8.setValue(uint8, forKey: "UInt8")
let uint8Value = cacheUInt8.value(forKey: "UInt8")
XCTAssertNotNil(uint8Value)
XCTAssertEqual(uint8Value!, uint8)
let cacheUInt16 = MemoryCache<UInt16>()
let uint16 = UInt16(UInt16.max)
cacheUInt16.setValue(uint16, forKey: "UInt16")
let uint16Value = cacheUInt16.value(forKey: "UInt16")
XCTAssertNotNil(uint16Value)
XCTAssertEqual(uint16Value!, uint16)
let cacheUInt32 = MemoryCache<UInt32>()
let uint32 = UInt32(UInt32.max)
cacheUInt32.setValue(uint32, forKey: "UInt32")
let uint32Value = cacheUInt32.value(forKey: "UInt32")
XCTAssertNotNil(uint32Value)
XCTAssertEqual(uint32Value!, uint32)
let cacheUInt64 = MemoryCache<UInt64>()
let uint64 = UInt64(UInt64.max)
cacheUInt64.setValue(uint64, forKey: "UInt64")
let uint64Value = cacheUInt64.value(forKey: "UInt64")
XCTAssertNotNil(uint64Value)
XCTAssertEqual(uint64Value!, uint64)
}
func testFloatingPoint() {
let cacheFloat = MemoryCache<Float>()
let float = Float(Float.pi)
cacheFloat.setValue(float, forKey: "Float")
let floatValue = cacheFloat.value(forKey: "Float")
XCTAssertNotNil(floatValue)
XCTAssertEqual(floatValue!, float)
let negFloat = Float(-Float.pi)
cacheFloat.setValue(negFloat, forKey: "negFloat")
let negFloatValue = cacheFloat.value(forKey: "negFloat")
XCTAssertNotNil(negFloatValue)
XCTAssertEqual(negFloatValue!, negFloat)
let infFloat = Float.infinity
cacheFloat.setValue(infFloat, forKey: "infFloat")
let infFloatValue = cacheFloat.value(forKey: "infFloat")
XCTAssertNotNil(infFloatValue)
XCTAssertEqual(infFloatValue!, infFloat)
let nanFloat = Float.nan
cacheFloat.setValue(nanFloat, forKey: "nanFloat")
let nanFloatValue = cacheFloat.value(forKey: "nanFloat")
XCTAssertNotNil(nanFloatValue)
XCTAssertEqual(nanFloatValue!.isNaN, nanFloat.isNaN)
let cacheDouble = MemoryCache<Double>()
let double = Double(Double.pi)
cacheDouble.setValue(double, forKey: "Double")
let doubleValue = cacheDouble.value(forKey: "Double")
XCTAssertNotNil(doubleValue)
XCTAssertEqual(doubleValue!, double)
let negDouble = Double(-Double.pi)
cacheDouble.setValue(negDouble, forKey: "negDouble")
let negDoubleValue = cacheDouble.value(forKey: "negDouble")
XCTAssertNotNil(negDoubleValue)
XCTAssertEqual(negDoubleValue!, negDouble)
let infDouble = Double.infinity
cacheDouble.setValue(infDouble, forKey: "infDouble")
let infDoubleValue = cacheDouble.value(forKey: "infDouble")
XCTAssertNotNil(infDoubleValue)
XCTAssertEqual(infDoubleValue!, infDouble)
let nanDouble = Double.nan
cacheDouble.setValue(nanDouble, forKey: "nanDouble")
let nanDoubleValue = cacheDouble.value(forKey: "nanDouble")
XCTAssertNotNil(nanDoubleValue)
XCTAssertEqual(nanDoubleValue!.isNaN, nanDouble.isNaN)
}
}
#if os(Linux)
extension MemoryCacheTests {
static var allTests : [(String, (MemoryCacheTests) -> () throws -> Void)] {
return [
("testIntValues", testIntValues),
("testDoubleValues", testDoubleValues),
("testStringValues", testStringValues),
("testStructValues", testStructValues),
("testClassValues", testClassValues),
("testRemove", testRemove),
("testRemoveAll", testRemoveAll),
("testExpiration", testExpiration),
("testRemoveExpired", testRemoveExpired),
("testExpirationInterval", testExpirationInterval),
("testRemoveItemsOlderThan", testRemoveItemsOlderThan),
("testInteger", testInteger),
("testFloatingPoint", testFloatingPoint),
]
}
}
#endif
| mit | 015e1a11c2cec3e3a1d94f74d0323381 | 34.363897 | 83 | 0.632637 | 4.384369 | false | true | false | false |
rinov/Gryphon | Gryphon/Task.swift | 1 | 2718 | //
// Gryphon
// Created by rinov on 9/17/16.
// Copyright © 2016 rinov. All rights reserved.
//
import Foundation
// `Result` represents API response that either successful or failure.
public enum APIResult<T> {
case response(T)
case error(Error)
}
public final class Task<Response,Error> {
// Initialization handler.
public typealias Initializer = (_: @escaping (APIResult<Response>) -> Void) -> Void
// The default value of maximum retry count.
fileprivate let maximumRetryCount: Int = 10
// The default value of maximum interval time(ms).
fileprivate let maximumIntervalTime: Double = 10000.0
// Result handler.
fileprivate var response: ((APIResult<Response>) -> Void)?
// Initializer handler.
fileprivate var initializer: Initializer?
// Retry count
fileprivate lazy var retry: Int = 0
// Interval time of request
fileprivate lazy var interval: Double = 0.0
// API response handler.
@discardableResult
public func response(_ handler: @escaping (APIResult<Response>) -> Void) -> Self {
response = handler
return self
}
// The maximum number of retry.
public func retry(max times: Int) -> Self {
retry = times
return self
}
// The time of interval for API request.
public func interval(milliseconds ms: Double) -> Self {
interval = ms
return self
}
// Initializing by closure of `initializar`.
public init(initClosuer: @escaping Initializer ) {
initializer = initClosuer
executeRequest()
}
// MARK: Private Methods
fileprivate func executeRequest() {
initializer?({ result in
switch result {
case let .response(data):
self.response?(APIResult.response(data))
case let .error(data):
self.response?(APIResult.error(data))
self.doRetry()
}
})
}
// If `retry` count is one or more.
fileprivate func doRetry() {
if retry > maximumRetryCount {
fatalError("The retry count is too many.\nPlease check the maximum retry count again.")
}
if retry > 0 {
retry -= 1
if interval > maximumIntervalTime {
fatalError("The interval time is too much.\nPlease check the maximum interval time again.")
}
let delayTime = DispatchTime.now() + Double(Int64( interval / 1000.0 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: delayTime) {
self.executeRequest()
}
}
}
}
| mit | 975ea2e13ba957cba61a0416e9f4f023 | 27.904255 | 128 | 0.599558 | 4.692573 | false | false | false | false |
xuech/OMS-WH | OMS-WH/Classes/OrderDetail/ViewModel/OrderDetailViewModel.swift | 1 | 9812 | //
// OrderDetailViewModel.swift
// OMS-WH
//
// Created by ___Gwy on 2017/9/11.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
import ObjectMapper
class OrderDetailViewModel: NSObject {
// func requestOrderDetail(_ soNo:String, _ finished: @escaping (_ data: OrderDetailModel?,_ error: NSError?)->Void) {
// XCHRefershUI.show()
// moyaNetWork.request(.commonRequst(paramters: ["sONo":soNo],api:"oms-api-v3/order/detail/orderDetail"), completion: { (result) in
// XCHRefershUI.dismiss()
// switch result {
// case let .success(moyaResponse):
// do {
// let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
// let data = try moyaJSON.mapJSON() as! [String:AnyObject]
// guard data["code"] as! Int == 0 else
// {
// SVProgressHUD.showError(data["msg"]! as! String)
// return
// }
// let info = data["info"] as! [String:AnyObject]
// finished(OrderDetailModel.init(dict: info), nil)
// }
// catch {}
// case .failure(_):
// finished(nil,nil)
// SVProgressHUD.showError("网络请求错误")
// break
// }
//
// })
// }
//订单详情-销售下单物料信息
// func requestInitMed(_ api:String, _ param:[String:String], _ finished: @escaping (_ data: [OMSOrderMetailsModel]?,_ error: NSError?)->Void) {
// moyaNetWork.request(.commonRequst(paramters: param, api: api), completion: { (result) in
// switch result {
// case let .success(moyaResponse):
// do {
// let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
// let data = try moyaJSON.mapJSON() as! [String:AnyObject]
// guard data["code"] as! Int == 0 else
// {
// SVProgressHUD.showError(data["msg"]! as! String)
// return
// }
// if let info = data["info"] as? [[String:AnyObject]]{
// finished(info, nil)
// }
// }
// catch {}
// case .failure(_):
// finished(nil,nil)
// SVProgressHUD.showError("网络请求错误")
// break
// }
//
// })
// }
// 请求订单详情-精确订单信息
func requestMed(_ api:String, _ param:[String:String], _ finished: @escaping (_ data: [[String:AnyObject]]?,_ error: NSError?)->Void) {
moyaNetWork.request(.commonRequst(paramters: param, api: api), completion: { (result) in
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(data["msg"]! as! String)
return
}
if let info = data["info"] as? [[String:AnyObject]]{
finished(info, nil)
}
}
catch {}
case .failure(_):
finished(nil,nil)
SVProgressHUD.showError("网络请求错误")
break
}
})
}
func requestKitData(_ api:String, _ param:[String:String], _ finished: @escaping (_ data: [KitModel],_ error: NSError?)->Void) {
moyaNetWork.request(.commonRequst(paramters: param, api: api), completion: { (result) in
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(data["msg"]! as! String)
return
}
if let info = data["info"] as? [[String:AnyObject]]{
let kitsModels = Mapper<KitModel>().mapArray(JSONArray: info)
// var child = [KitModel]()
// for item in info{
// child.append(KitModel.m)
// }
finished(kitsModels, nil)
}
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
})
}
func requestKitDetailData(_ api:String, _ param:[String:String], _ finished: @escaping (_ data: KitDetailModel?,_ error: NSError?)->Void) {
moyaNetWork.request(.commonRequst(paramters: param, api: api), completion: { (result) in
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(data["msg"]! as! String)
return
}
if let info = data["info"] as? [String:AnyObject]{
finished(KitDetailModel.init(dict: info), nil)
}
}
catch {}
case .failure(_):
finished(nil,nil)
SVProgressHUD.showError("网络请求错误")
break
}
})
}
func requestOutBoundSecondData(_ api:String, _ param:[String:String], _ finished: @escaping (_ data: [OutBoundDetailModel]?,_ error: NSError?)->Void) {
XCHRefershUI.show()
moyaNetWork.request(.commonRequst(paramters: param, api: api), completion: { (result) in
XCHRefershUI.dismiss()
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(data["msg"]! as! String)
return
}
if let info = data["info"] as? [[String:AnyObject]]{
var child = [OutBoundDetailModel]()
for item in info{
child.append(OutBoundDetailModel.init(dict: item))
}
finished(child, nil)
}
}
catch {}
case .failure(_):
finished(nil,nil)
SVProgressHUD.showError("网络请求错误")
break
}
})
}
func requestOutBoundFirstData(_ api:String, _ param:[String:String], _ finished: @escaping (_ data: [String:AnyObject]?,_ error: NSError?)->Void) {
moyaNetWork.request(.commonRequst(paramters: param, api: api), completion: { (result) in
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(data["msg"]! as! String)
return
}
if let info = data["info"] as? [String:AnyObject]{
finished(info, nil)
}
}
catch {}
case .failure(_):
finished(nil,nil)
SVProgressHUD.showError("网络请求错误")
break
}
})
}
func requestFeedBackData(_ api:String, _ param:[String:String], _ finished: @escaping (_ data: [FeedBackMedModel]?,_ info: [[String:AnyObject]]?,_ error: NSError?)->Void) {
moyaNetWork.request(.commonRequst(paramters: param, api: api), completion: { (result) in
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(data["msg"]! as! String)
return
}
if let info = data["info"] as? [[String:AnyObject]]{
let childrenCategory = Mapper<FeedBackMedModel>().mapArray(JSONArray: info)
finished(childrenCategory, info, nil)
}
}
catch {}
case .failure(_):
finished(nil,nil,nil)
SVProgressHUD.showError("网络请求错误")
break
}
})
}
}
| mit | 98e775a4e47fd4a55d44b531911fadd1 | 39.95339 | 177 | 0.458976 | 5.215866 | false | false | false | false |
benlangmuir/swift | test/Serialization/load-target-normalization.swift | 11 | 8959 | // RUN: %empty-directory(%t/ForeignModule.swiftmodule)
// RUN: touch %t/ForeignModule.swiftmodule/garbage-garbage-garbage.swiftmodule
// SR-12363: This test crashes on next branch.
// XFAIL: asserts
// Test format: We try to import ForeignModule with architectures besides
// garbage-garbage-garbage and check the target triple listed in the error
// message to make sure it was normalized correctly. This works in lieu of a
// mechanism to query the compiler for normalized triples.
//
// The extra flags in the RUN lines serve the following purposes:
//
// * "-parse-stdlib" ensures we don't reject any of these for not having an
// appropriate standard library built.
// * "-Xcc -arch -Xcc i386" makes sure the clang importer doesn't reject triples
// clang considers invalid.
import ForeignModule
// CHECK: error: could not find module 'ForeignModule'
// CHECK-SAME: '[[NORM]]'
// Run lines for individual test cases follow.
//
// OSES
//
// OS version numbers should be stripped.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macosx10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s
// macos, macosx, and darwin should all normalize to macos.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macos10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macosx10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-darwin46.0 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s
// ios, tvos, watchos should be accepted.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-tvos40 2>&1 | %FileCheck -DNORM=arm64-apple-tvos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-watchos9.1.1 2>&1 | %FileCheck -DNORM=arm64-apple-watchos %s
// Other OSes should be passed through without version stripping. We can't test
// a totally garbage case because we'll get diag::error_unsupported_target_os.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-linux40.04 2>&1 | %FileCheck -DNORM=x86_64-apple-linux40.04 %s
//
// VENDORS
//
// If the OS looks like an Apple OS, vendor should be normalized to apple.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-unknown-macos10.42 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64--ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-ibm-tvos40 2>&1 | %FileCheck -DNORM=arm64-apple-tvos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-snapple-watchos9.1.1 2>&1 | %FileCheck -DNORM=arm64-apple-watchos %s
//
// ARCHITECTURES
//
// arm64 and aarch64 are normalized to arm64.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target aarch64-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64-apple-ios %s
// armv7s, armv7k, armv7, arm64_32, arm64e should be accepted.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7s-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7s-apple-ios %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7k-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7k-apple-ios %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target armv7-apple-ios40.0 2>&1 | %FileCheck -DNORM=armv7-apple-ios %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64_32-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64_32-apple-ios %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target arm64e-apple-ios40.0 2>&1 | %FileCheck -DNORM=arm64e-apple-ios %s
// x86_64h should be accepted.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64h-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64h-apple-macos %s
// x64_64 and amd64 are normalized to x86_64.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target amd64-apple-macos10.11 2>&1 | %FileCheck -DNORM=x86_64-apple-macos %s
// i[3-9]86 are normalized to i386.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i486-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i586-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i686-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i786-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i886-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i986-apple-macos10.11 2>&1 | %FileCheck -DNORM=i386-apple-macos %s
// Other arches should be passed through. We can't test a totally garbage case
// because we'll get diag::error_unsupported_target_arch.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target powerpc64-apple-macos10.11 2>&1 | %FileCheck -DNORM=powerpc64-apple-macos %s
//
// ENVIRONMENTS
//
// simulator should be permitted on the non-Mac operating systems.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-ios40.0-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-ios-simulator %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-tvos40-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-tvos-simulator %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-apple-watchos9.1.1-simulator 2>&1 | %FileCheck -DNORM=x86_64-apple-watchos-simulator %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-ios40.0-simulator 2>&1 | %FileCheck -DNORM=i386-apple-ios-simulator %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-tvos40-simulator 2>&1 | %FileCheck -DNORM=i386-apple-tvos-simulator %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-watchos9.1.1-simulator 2>&1 | %FileCheck -DNORM=i386-apple-watchos-simulator %s
// Other environments should be passed through.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i386-apple-ios40.0-in_spaaaaaaace 2>&1 | %FileCheck -DNORM=i386-apple-ios-in_spaaaaaaace %s
//
// DARWIN ONLY
//
// Non-isDarwinOS() OSes should have no normalization applied.
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target x86_64-unknown-linux40.04 2>&1 | %FileCheck -DNORM=x86_64-unknown-linux40.04 %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target aarch64--linux-android 2>&1 | %FileCheck -DNORM=aarch64--linux-android %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target amd64-ibm-linux40.04 2>&1 | %FileCheck -DNORM=amd64-ibm-linux40.04 %s
// RUN: not %target-swift-frontend %s -typecheck -I %t -parse-stdlib -Xcc -arch -Xcc i386 -target i986-snapple-haiku 2>&1 | %FileCheck -DNORM=i986-snapple-haiku %s
| apache-2.0 | d8e629f2de7623175c313a7c4d4859ea | 68.449612 | 192 | 0.7147 | 2.872395 | false | false | false | false |
lightsprint09/InTrain-ICE-API | ICEInformationiOS/StationSchedule+JSONSerialization.swift | 1 | 2703 | //
// Copyright (C) 2017 Lukas Schmidt.
//
// 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.
//
//
// StationSchedule+JSONSerialization.swift
// ICEInformation
//
// Created by Lukas Schmidt on 05.04.17.
//
import Foundation
import JSONCodable
extension StationSchedule: JSONDecodable, JSONEncodable {
public init(object: JSONObject) throws {
let decoder = JSONDecoder(object: object)
let scheduledArrivalTime: Double? = try decoder.decode("scheduledArrivalTime")
let scheduledDepartureTime: Double? = try decoder.decode("scheduledDepartureTime")
arrivalTime = Date(timeIntervalSince1970: (scheduledArrivalTime ?? scheduledDepartureTime!) * 0.001)
departureTime = Date(timeIntervalSince1970: (scheduledDepartureTime ?? scheduledArrivalTime!) * 0.001)
arrivalDelay = extractDelay(try decoder.decode("arrivalDelay"))
depatureDelay = extractDelay(try decoder.decode("departureDelay"))
}
public func toJSON() throws -> Any {
return try JSONEncoder.create({ (encoder) -> Void in
try encoder.encode(arrivalTime.timeIntervalSinceReferenceDate, key: "scheduledArrivalTime")
try encoder.encode(departureTime.timeIntervalSinceReferenceDate, key: "scheduledArrivalTime")
try encoder.encode(arrivalDelay, key: "arrivalDelay")
try encoder.encode(depatureDelay, key: "depatureDelay")
})
}
}
func extractDelay(_ delay:String?) -> TimeInterval? {
guard let delay = delay,
let delayTime = Double(delay.replacingOccurrences(of: "+", with: "")) else { return nil }
return delayTime * 60
}
| mit | 9df802f4fd4ea2b1ee259848213fa689 | 44.05 | 110 | 0.716611 | 4.527638 | false | false | false | false |
imk2o/MK2Router | MK2Router/Models/MessageProvider.swift | 1 | 816 | //
// MessageProvider.swift
// MK2Router
//
// Created by k2o on 2016/05/15.
// Copyright © 2016年 Yuichi Kobayashi. All rights reserved.
//
import UIKit
class MessageProvider {
static let shared: MessageProvider = MessageProvider()
fileprivate init() {
}
func sendMessage(_ message: Message, delay: TimeInterval, handler: () -> Void) {
let notification = UILocalNotification()
notification.fireDate = Date(timeIntervalSinceNow: delay)
notification.timeZone = TimeZone.current
notification.alertBody = "\(message.title)へのメッセージが送信されました!"
notification.userInfo = ["itemID": message.itemID]
UIApplication.shared.scheduleLocalNotification(notification)
handler()
}
}
| mit | 9846e2fb7974d2879c65a249e558ead8 | 25.931034 | 84 | 0.65685 | 4.488506 | false | false | false | false |
TCA-Team/iOS | TUM Campus App/NewsSource.swift | 1 | 2989 | //
// NewsSource.swift
// Campus
//
// This file is part of the TUM Campus App distribution https://github.com/TCA-Team/iOS
// Copyright (c) 2018 TCA
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, version 3.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
extension News {
struct Source: OptionSet {
let rawValue: Int
}
}
extension News.Source {
init(identifier: Int) {
self.init(rawValue: 1 << (identifier - 1))
}
static let tumNews = News.Source(identifier: 1)
static let movies = News.Source(identifier: 2)
static let studentNews = News.Source(identifier: 4)
static let pressNews = News.Source(identifier: 5)
static let operatingSystems = News.Source(identifier: 6)
static let newsspreadFMI = News.Source(identifier: 7)
static let newsspreadChemistry = News.Source(identifier: 8)
static let newsspreadSG = News.Source(identifier: 9)
static let newsspreadWeihenstephan = News.Source(identifier: 13)
static let alumni = News.Source(identifier: 14)
static let impulsiv = News.Source(identifier: 15)
static let all = News.Source(rawValue: .max)
static let newsSpread: News.Source = [
.newsspreadFMI,
.newsspreadChemistry,
.newsspreadSG,
.newsspreadWeihenstephan
]
static var restOfNews: News.Source {
return News.Source.all.subtracting([.movies, .newsSpread])
}
}
extension News.Source {
var titleColor: UIColor {
switch self {
case .movies:
return Constants.tuFilmTitleColor
case .impulsiv:
return Constants.tumBlue
case News.Source.newsSpread:
return .orange
case News.Source.pressNews:
return .blue
case News.Source.studentNews:
return .red
case News.Source.tumNews:
return Constants.tumBlue
default:
return Constants.newsTitleColor
}
}
var title: String {
switch self {
case .movies:
return "TU Film"
case .impulsiv:
return "Impulsiv"
case News.Source.newsSpread:
return "Newsspread"
case News.Source.pressNews:
return "Press News"
case News.Source.studentNews:
return "Student News"
case News.Source.tumNews:
return "TUM News"
default:
return "News"
}
}
}
| gpl-3.0 | c2608ef313c844ded9b32d786c7c00e5 | 27.740385 | 88 | 0.629977 | 4.111417 | false | false | false | false |
vmalakhovskiy/Gemini | Gemini/Gemini/Presentation/ViewController.swift | 1 | 4941 | //
// ViewController.swift
// Gemini
//
// Created by Vitaliy Malakhovskiy on 7/10/16.
// Copyright © 2016 Vitalii Malakhovskyi. All rights reserved.
//
import Cocoa
import ReactiveCocoa
import Result
class ViewController: NSViewController {
private let viewModel: ViewModel
private let cocoaAction: CocoaAction
@IBOutlet weak var xrayImageView: NSImageView!
@IBOutlet weak var compareButton: NSButton!
@IBOutlet weak var comparingImageView: FolderPickerImageView!
@IBOutlet weak var comparableImageView: FolderPickerImageView!
@IBOutlet weak var infoLabel: NSTextField!
@IBOutlet weak var comparingViewLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var comparableViewTrailingConstraint: NSLayoutConstraint!
init(viewModel: ViewModel) {
self.viewModel = viewModel
self.cocoaAction = CocoaAction(self.viewModel.compareAction, input: ())
super.init(nibName: "ViewController", bundle: nil)! // Yes, i want to crash the app if nib not found
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
setupCompareButton()
setupBindings()
}
func setupCompareButton() {
compareButton.target = cocoaAction
compareButton.action = CocoaAction.selector
}
func setupBindings() {
viewModel.comparingDirectoryPath <~ comparingImageView.droppedFilePath.producer.ignoreNil()
viewModel.comparableDirectoryPath <~ comparableImageView.droppedFilePath.producer.ignoreNil()
viewModel.compareAction.executing.producer
.skip(1)
.startWithNext { [weak self] executing in
guard let strongSelf = self else { return }
if executing {
strongSelf.infoLabel.stringValue = "Scanning..."
strongSelf.comparingViewLeadingConstraint.constant = CGRectGetWidth(strongSelf.view.frame) / 2 - CGRectGetWidth(strongSelf.comparingImageView.frame) / 2
strongSelf.comparableViewTrailingConstraint.constant = CGRectGetWidth(strongSelf.view.frame) / 2 - CGRectGetWidth(strongSelf.comparableImageView.frame) / 2
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.5
context.allowsImplicitAnimation = true
strongSelf.view.layoutSubtreeIfNeeded()
}, completionHandler: nil)
strongSelf.xrayImageView.addAnimationForKey(CAKeyframeAnimation.self, { xray in
xray.keyPath = "position.y"
xray.values = [0, CGRectGetHeight(strongSelf.view.frame) + CGRectGetHeight(strongSelf.xrayImageView.frame)]
xray.duration = 1
xray.beginTime = CACurrentMediaTime() + 0.5
xray.autoreverses = true
xray.additive = true
xray.repeatCount = FLT_MAX
xray.calculationMode = kCAAnimationPaced
xray.rotationMode = kCAAnimationRotateAuto
return "xray"
})
} else {
strongSelf.infoLabel.stringValue = "Ready for scan"
strongSelf.xrayImageView.layer?.removeAnimationForKey("xray")
strongSelf.comparingViewLeadingConstraint.constant = 20
strongSelf.comparableViewTrailingConstraint.constant = 20
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.5
context.allowsImplicitAnimation = true
strongSelf.view.layoutSubtreeIfNeeded()
}, completionHandler: nil)
}
}
viewModel.compareAction.enabled.producer
.takeUntil(rac_willDeallocSignalProducer())
.startWithNext { [weak self] in
self?.compareButton.enabled = $0
}
viewModel.compareAction.values.observeNext { [weak self] equal in
guard let strongSelf = self, window = strongSelf.view.window else { return }
let alert = NSAlert()
alert.addButtonWithTitle("OK")
alert.messageText = "Finished"
alert.informativeText = equal ? "Directories are equal" : "Directories are NOT equal"
alert.icon = equal ? NSImage(named: "Success") : NSImage(named: "Failure")
alert.alertStyle = .WarningAlertStyle
alert.beginSheetModalForWindow(window, completionHandler: nil)
}
}
}
class ViewControllerFactory {
static func defaultViewController() -> ViewController {
return ViewController(viewModel: ViewModelFactory.defaultViewModel())
}
}
| mit | 87fa85a29930ad0b74666426b6cb7caf | 39.491803 | 175 | 0.626113 | 5.613636 | false | false | false | false |
danieleggert/HTTPServer | HTTPServer/Utilities.swift | 1 | 4901 | //
// Utilities.swift
// HTTPServer
//
// Created by Daniel Eggert on 04/05/2015.
// Copyright (c) 2015 Wire. All rights reserved.
//
import Foundation
extension NSDate {
/// Returns the date formatted according to RFC 2616 section 3.3.1
/// specifically RFC 822, updated by RFC 1123
public func HTTPFormattedDateString(timeZone: NSTimeZone = NSTimeZone.systemTimeZone()) -> String {
let timeZoneString = timeZone.abbreviation ?? "GMT"
var dateString: String? = nil
timeZoneString.withCString { (timeZonePointer) -> () in
var t = time_t(self.timeIntervalSince1970)
var timeptr = tm()
gmtime_r(&t, &timeptr)
timeptr.tm_zone = UnsafeMutablePointer<Int8>(timeZonePointer)
let locale = newlocale(0, "POSIX", locale_t())
var buffer = ContiguousArray<Int8>(count: 40, repeatedValue: 0)
let bufferSize = buffer.count
buffer.withUnsafeMutableBufferPointer { (inout b: UnsafeMutableBufferPointer<Int8>) -> () in
if 0 < strftime_l(b.baseAddress, bufferSize, "%a, %d %b %Y %H:%M:%S %Z", &timeptr, locale) {
dateString = String.fromCString(UnsafePointer<CChar>(b.baseAddress))
}
}
freelocale(locale)
}
return dateString!
}
}
extension Int {
public var defaultHTTPStatusDescription: String? {
switch self {
case 100: return "Continue"
case 101: return "Switching Protocols"
case 102: return "Processing"
case 200: return "Ok"
case 201: return "Created"
case 202: return "Accepted"
case 203: return "Non-Authoritative Information"
case 204: return "No Content"
case 205: return "Reset Content"
case 206: return "Partial Content"
case 207: return "Multi-Status"
case 208: return "Already Reported"
case 226: return "IM Used"
case 300: return "Multiple Choices"
case 301: return "Moved Permanently"
case 302: return "Found"
case 303: return "See Other"
case 304: return "Not Modified"
case 305: return "Use Proxy"
case 306: return "Switch Proxy"
case 307: return "Temporary Redirect"
case 308: return "Permanent Redirect"
case 400: return "Bad Request"
case 401: return "Unauthorized"
case 402: return "Payment Required"
case 403: return "Forbidden"
case 404: return "Not Found"
case 405: return "Method Not Allowed"
case 406: return "Not Acceptable"
case 407: return "Proxy Authentication Required"
case 408: return "Request Timeout"
case 409: return "Conflict"
case 410: return "Gone"
case 411: return "Length Required"
case 412: return "Precondition Failed"
case 413: return "Request Entity Too Large"
case 414: return "Request-URI Too Long"
case 415: return "Unsupported Media Type"
case 416: return "Requested Range Not Satisfiable"
case 417: return "Expectation Failed"
case 418: return "I'm a teapot"
case 419: return "Authentication Timeout"
case 420: return "Method Failure"
case 421: return "Misdirected Request"
case 422: return "Unprocessed Entity"
case 423: return "Locked"
case 424: return "Failed Dependency"
case 426: return "Upgrade Required"
case 428: return "Precondition Required"
case 429: return "Too Many Requests"
case 431: return "Request Header Fields Too Large"
case 440: return "Login Timeout"
case 444: return "No Response"
case 449: return "Retry With"
case 450: return "Blocked by Windows Parental Controls"
case 451: return "Unavailable For Legal Reasons"
case 494: return "Request Header Too Large"
case 495: return "Cert Error"
case 496: return "No Cert"
case 497: return "HTTP to HTTPS"
case 498: return "Token expired/invalid"
case 499: return "Client Closed Request"
case 500: return "Internal Server Error"
case 501: return "Not Implemented"
case 502: return "Bad Gateway"
case 503: return "Service Unavailable"
case 504: return "Gateway Timeout"
case 505: return "HTTP Version Not Supported"
case 506: return "Variant Also Negotiates"
case 507: return "Insufficient Storage"
case 508: return "Loop Detected"
case 509: return "Bandwidth Limit Exceeded"
case 510: return "Not Extended"
case 511: return "Network Authentication Required"
case 598: return "Network read timeout error"
case 599: return "Network connect timeout error"
default: return nil
}
}
}
| isc | 7bfe163e55e445d1ca3ac70e0a3af52f | 38.208 | 108 | 0.618853 | 4.584659 | false | false | false | false |
mpullman/SalesforceMobileSDK-iOS | external/ocmock/Examples/SwiftExamples/SwiftExamples/DetailViewController.swift | 5 | 2553 | //
// DetailViewController.swift
// SwiftExamples
//
// Created by Erik Doernenburg on 11/06/2014.
// Copyright (c) 2014 Mulle Kybernetik. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UISplitViewControllerDelegate {
@IBOutlet var detailDescriptionLabel: UILabel
var masterPopoverController: UIPopoverController? = nil
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: AnyObject = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.description
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = "Master" // NSLocalizedString(@"Master", @"Master")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
}
| apache-2.0 | b34c80bacebb705e597bd1c1c6c6509a | 37.104478 | 238 | 0.713278 | 6.078571 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Settings/IdentityServer/SettingsIdentityServerViewController.swift | 1 | 17399 | // File created from ScreenTemplate
// $ createScreen.sh Test SettingsIdentityServer
/*
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 UIKit
final class SettingsIdentityServerViewController: UIViewController {
// MARK: - Properties
// MARK: Outlets
@IBOutlet private weak var scrollView: UIScrollView!
@IBOutlet weak var identityServerContainer: UIView!
@IBOutlet weak var identityServerLabel: UILabel!
@IBOutlet weak var identityServerTextField: UITextField!
@IBOutlet private weak var messageLabel: UILabel!
@IBOutlet weak var addOrChangeButtonContainer: UIView!
@IBOutlet private weak var addOrChangeButton: UIButton!
@IBOutlet weak var disconnectMessageLabel: UILabel!
@IBOutlet weak var disconnectButtonContainer: UIView!
@IBOutlet weak var disconnectButton: UIButton!
// MARK: Private
private var viewModel: SettingsIdentityServerViewModelType!
private var theme: Theme!
private var keyboardAvoider: KeyboardAvoider?
private var errorPresenter: MXKErrorPresentation!
private var activityPresenter: ActivityIndicatorPresenter!
private var viewState: SettingsIdentityServerViewState?
private var displayMode: SettingsIdentityServerDisplayMode?
private weak var alertController: UIAlertController?
private var serviceTermsModalCoordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter?
private var serviceTermsModalCoordinatorBridgePresenterOnComplete: ((Bool) -> Void)?
// MARK: - Setup
class func instantiate(with viewModel: SettingsIdentityServerViewModelType) -> SettingsIdentityServerViewController {
let viewController = StoryboardScene.SettingsIdentityServerViewController.initialScene.instantiate()
viewController.viewModel = viewModel
viewController.theme = ThemeService.shared().theme
return viewController
}
// MARK: - Life cycle
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.title = VectorL10n.identityServerSettingsTitle
self.setupViews()
self.keyboardAvoider = KeyboardAvoider(scrollViewContainerView: self.view, scrollView: self.scrollView)
self.activityPresenter = ActivityIndicatorPresenter()
self.errorPresenter = MXKErrorAlertPresentation()
self.registerThemeServiceDidChangeThemeNotification()
self.update(theme: self.theme)
self.viewModel.viewDelegate = self
self.viewModel.process(viewAction: .load)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.keyboardAvoider?.startAvoiding()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
self.keyboardAvoider?.stopAvoiding()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return self.theme.statusBarStyle
}
// MARK: - Private
private func update(theme: Theme) {
self.theme = theme
self.view.backgroundColor = theme.headerBackgroundColor
if let navigationBar = self.navigationController?.navigationBar {
theme.applyStyle(onNavigationBar: navigationBar)
}
self.identityServerContainer.backgroundColor = theme.backgroundColor
self.identityServerLabel.textColor = theme.textPrimaryColor
theme.applyStyle(onTextField: self.identityServerTextField)
self.identityServerTextField.textColor = theme.textSecondaryColor
self.messageLabel.textColor = theme.textPrimaryColor
self.addOrChangeButtonContainer.backgroundColor = theme.backgroundColor
theme.applyStyle(onButton: self.addOrChangeButton)
self.disconnectMessageLabel.textColor = theme.textPrimaryColor
self.disconnectButtonContainer.backgroundColor = theme.backgroundColor
theme.applyStyle(onButton: self.disconnectButton)
self.disconnectButton.setTitleColor(self.theme.warningColor, for: .normal)
}
private func registerThemeServiceDidChangeThemeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeServiceDidChangeTheme, object: nil)
}
@objc private func themeDidChange() {
self.update(theme: ThemeService.shared().theme)
}
private func setupViews() {
self.scrollView.keyboardDismissMode = .interactive
self.identityServerLabel.text = VectorL10n.identityServerSettingsTitle
self.identityServerTextField.placeholder = VectorL10n.identityServerSettingsPlaceHolder
self.identityServerTextField.addTarget(self, action: #selector(identityServerTextFieldDidChange(_:)), for: .editingChanged)
self.identityServerTextField.addTarget(self, action: #selector(identityServerTextFieldDidEndOnExit(_:)), for: .editingDidEndOnExit)
self.disconnectMessageLabel.text = VectorL10n.identityServerSettingsDisconnectInfo
self.disconnectButton.setTitle(VectorL10n.identityServerSettingsDisconnect, for: .normal)
self.disconnectButton.setTitle(VectorL10n.identityServerSettingsDisconnect, for: .highlighted)
}
private func render(viewState: SettingsIdentityServerViewState) {
switch viewState {
case .loading:
self.renderLoading()
case .loaded(let displayMode):
self.renderLoaded(displayMode: displayMode)
case .presentTerms(let session, let accessToken, let baseUrl, let onComplete):
self.presentTerms(session: session, accessToken: accessToken, baseUrl: baseUrl, onComplete: onComplete)
case .alert(let alert, let onContinue):
self.renderAlert(alert: alert, onContinue: onContinue)
case .error(let error):
self.render(error: error)
}
}
private func renderLoading() {
self.activityPresenter.presentActivityIndicator(on: self.view, animated: true)
}
private func renderLoaded(displayMode: SettingsIdentityServerDisplayMode) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.displayMode = displayMode
switch displayMode {
case .noIdentityServer:
self.renderNoIdentityServer()
case .identityServer(let host):
self.renderIdentityServer(host: host)
}
}
private func renderNoIdentityServer() {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.identityServerTextField.text = nil
self.messageLabel.text = VectorL10n.identityServerSettingsNoIsDescription
self.addOrChangeButton.setTitle(VectorL10n.identityServerSettingsAdd, for: .normal)
self.addOrChangeButton.setTitle(VectorL10n.identityServerSettingsAdd, for: .highlighted)
self.addOrChangeButton.isEnabled = false
self.disconnectMessageLabel.isHidden = true
self.disconnectButtonContainer.isHidden = true
}
private func renderIdentityServer(host: String) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.identityServerTextField.text = host
self.messageLabel.text = VectorL10n.identityServerSettingsDescription(host.hostname())
self.addOrChangeButton.setTitle(VectorL10n.identityServerSettingsChange, for: .normal)
self.addOrChangeButton.setTitle(VectorL10n.identityServerSettingsChange, for: .highlighted)
self.addOrChangeButton.isEnabled = false
self.disconnectMessageLabel.isHidden = false
self.disconnectButtonContainer.isHidden = false
}
private func presentTerms(session: MXSession, accessToken: String, baseUrl: String, onComplete: @escaping (Bool) -> Void) {
let serviceTermsModalCoordinatorBridgePresenter = ServiceTermsModalCoordinatorBridgePresenter(session: session, baseUrl: baseUrl, serviceType: MXServiceTypeIdentityService, accessToken: accessToken)
serviceTermsModalCoordinatorBridgePresenter.present(from: self, animated: true)
serviceTermsModalCoordinatorBridgePresenter.delegate = self
self.serviceTermsModalCoordinatorBridgePresenter = serviceTermsModalCoordinatorBridgePresenter
self.serviceTermsModalCoordinatorBridgePresenterOnComplete = onComplete
}
private func hideTerms(accepted: Bool) {
guard let serviceTermsModalCoordinatorBridgePresenterOnComplete = self.serviceTermsModalCoordinatorBridgePresenterOnComplete else {
return
}
self.serviceTermsModalCoordinatorBridgePresenter?.dismiss(animated: true, completion: nil)
self.serviceTermsModalCoordinatorBridgePresenter = nil
serviceTermsModalCoordinatorBridgePresenterOnComplete(accepted)
self.serviceTermsModalCoordinatorBridgePresenterOnComplete = nil
}
private func renderAlert(alert: SettingsIdentityServerAlert, onContinue: @escaping () -> Void) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
switch alert {
case .addActionAlert(.invalidIdentityServer(let newHost)),
.changeActionAlert(.invalidIdentityServer(let newHost)):
self.showAlert(title: nil,
message: VectorL10n.identityServerSettingsAlertErrorInvalidIdentityServer(newHost),
continueButtonTitle: nil,
cancelButtonTitle: VectorL10n.cancel,
onContinue: onContinue)
case .addActionAlert(.noTerms),
.changeActionAlert(.noTerms):
self.showAlert(title: VectorL10n.identityServerSettingsAlertNoTermsTitle,
message: VectorL10n.identityServerSettingsAlertNoTerms,
continueButtonTitle: VectorL10n.continue,
cancelButtonTitle: VectorL10n.cancel,
onContinue: onContinue)
case .addActionAlert(.termsNotAccepted(let newHost)),
.changeActionAlert(.termsNotAccepted(let newHost)):
self.showAlert(title: nil,
message: VectorL10n.identityServerSettingsAlertErrorTermsNotAccepted(newHost.hostname()),
continueButtonTitle: nil,
cancelButtonTitle: VectorL10n.cancel,
onContinue: onContinue)
case .changeActionAlert(.stillSharing3Pids(let oldHost, _)):
self.showAlert(title: VectorL10n.identityServerSettingsAlertChangeTitle,
message: VectorL10n.identityServerSettingsAlertDisconnectStillSharing3pid(oldHost.hostname()),
continueButtonTitle: VectorL10n.identityServerSettingsAlertDisconnectStillSharing3pidButton,
cancelButtonTitle: VectorL10n.cancel,
onContinue: onContinue)
case .changeActionAlert(.doubleConfirmation(let oldHost, let newHost)):
self.showAlert(title: VectorL10n.identityServerSettingsAlertChangeTitle,
message: VectorL10n.identityServerSettingsAlertChange(oldHost.hostname(), newHost.hostname()),
continueButtonTitle: VectorL10n.continue,
cancelButtonTitle: VectorL10n.cancel,
onContinue: onContinue)
case .disconnectActionAlert(.stillSharing3Pids(let oldHost)):
self.showAlert(title: VectorL10n.identityServerSettingsAlertDisconnectTitle,
message: VectorL10n.identityServerSettingsAlertDisconnectStillSharing3pid(oldHost.hostname()),
continueButtonTitle: VectorL10n.identityServerSettingsAlertDisconnectStillSharing3pidButton,
cancelButtonTitle: VectorL10n.cancel,
onContinue: onContinue)
case .disconnectActionAlert(.doubleConfirmation(let oldHost)):
self.showAlert(title: VectorL10n.identityServerSettingsAlertDisconnectTitle,
message: VectorL10n.identityServerSettingsAlertDisconnect(oldHost.hostname()),
continueButtonTitle: VectorL10n.identityServerSettingsAlertDisconnectButton,
cancelButtonTitle: VectorL10n.cancel,
onContinue: onContinue)
}
}
private func render(error: Error) {
self.activityPresenter.removeCurrentActivityIndicator(animated: true)
self.errorPresenter.presentError(from: self, forError: error, animated: true, handler: nil)
}
// MARK: - Alert
private func showAlert(title: String?, message: String, continueButtonTitle: String?, cancelButtonTitle: String, onContinue: @escaping () -> Void) {
guard self.alertController == nil else {
return
}
let alertController = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: cancelButtonTitle, style: .cancel, handler: { action in
}))
if let continueButtonTitle = continueButtonTitle {
alertController.addAction(UIAlertAction(title: continueButtonTitle, style: .default, handler: { action in
onContinue()
}))
}
self.present(alertController, animated: true, completion: nil)
self.alertController = alertController
}
private func hideAlert(animated: Bool) {
self.alertController?.dismiss(animated: true, completion: nil)
}
// MARK: - Actions
@objc private func identityServerTextFieldDidChange(_ textField: UITextField) {
self.addOrChangeButton.isEnabled = textField.text?.count ?? 0 > 0
&& (textField.text?.hostname() != self.viewModel.identityServer?.hostname())
}
@objc private func identityServerTextFieldDidEndOnExit(_ textField: UITextField) {
self.addOrChangeAction()
}
@IBAction private func addOrChangeButtonAction(_ sender: Any) {
self.addOrChangeAction()
}
private func addOrChangeAction() {
self.identityServerTextField.resignFirstResponder()
guard
let displayMode = displayMode,
let identityServer = identityServerTextField.text?.trimmingCharacters(in: .whitespaces),
!identityServer.isEmpty
else {
viewModel.process(viewAction: .load)
return
}
let viewAction: SettingsIdentityServerViewAction?
switch displayMode {
case .noIdentityServer:
viewAction = .add(identityServer: identityServer.makeURLValid())
case .identityServer:
viewAction = .change(identityServer: identityServer.makeURLValid())
}
if let viewAction = viewAction {
self.viewModel.process(viewAction: viewAction)
}
}
@IBAction private func disconnectButtonAction(_ sender: Any) {
self.viewModel.process(viewAction: .disconnect)
}
}
// MARK: - SettingsIdentityServerViewModelViewDelegate
extension SettingsIdentityServerViewController: SettingsIdentityServerViewModelViewDelegate {
func settingsIdentityServerViewModel(_ viewModel: SettingsIdentityServerViewModelType, didUpdateViewState viewState: SettingsIdentityServerViewState) {
self.viewState = viewState
self.render(viewState: viewState)
}
}
// MARK: - ServiceTermsModalCoordinatorBridgePresenterDelegate
extension SettingsIdentityServerViewController: ServiceTermsModalCoordinatorBridgePresenterDelegate {
func serviceTermsModalCoordinatorBridgePresenterDelegateDidAccept(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter) {
self.hideTerms(accepted: true)
}
func serviceTermsModalCoordinatorBridgePresenterDelegateDidDecline(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter, session: MXSession) {
self.hideTerms(accepted: false)
}
func serviceTermsModalCoordinatorBridgePresenterDelegateDidClose(_ coordinatorBridgePresenter: ServiceTermsModalCoordinatorBridgePresenter) {
self.hideTerms(accepted: false)
}
}
// MARK: - Private extension
fileprivate extension String {
func hostname() -> String {
return URL(string: self)?.host ?? self
}
func makeURLValid() -> String {
if self.hasPrefix("http://") || self.hasPrefix("https://") {
return self
} else {
return "https://" + self
}
}
}
| apache-2.0 | 8a1267e9de73b7bf55591bcd21471229 | 40.724221 | 206 | 0.699351 | 5.822959 | false | false | false | false |
uasys/swift | stdlib/public/core/CTypes.swift | 1 | 6861 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// C Primitive Types
//===----------------------------------------------------------------------===//
/// The C 'char' type.
///
/// This will be the same as either `CSignedChar` (in the common
/// case) or `CUnsignedChar`, depending on the platform.
public typealias CChar = Int8
/// The C 'unsigned char' type.
public typealias CUnsignedChar = UInt8
/// The C 'unsigned short' type.
public typealias CUnsignedShort = UInt16
/// The C 'unsigned int' type.
public typealias CUnsignedInt = UInt32
/// The C 'unsigned long' type.
public typealias CUnsignedLong = UInt
/// The C 'unsigned long long' type.
public typealias CUnsignedLongLong = UInt64
/// The C 'signed char' type.
public typealias CSignedChar = Int8
/// The C 'short' type.
public typealias CShort = Int16
/// The C 'int' type.
public typealias CInt = Int32
/// The C 'long' type.
#if os(Windows) && arch(x86_64)
public typealias CLong = Int32
#else
public typealias CLong = Int
#endif
/// The C 'long long' type.
#if os(Windows) && arch(x86_64)
public typealias CLongLong = Int
#else
public typealias CLongLong = Int64
#endif
/// The C 'float' type.
public typealias CFloat = Float
/// The C 'double' type.
public typealias CDouble = Double
// FIXME: long double
// FIXME: Is it actually UTF-32 on Darwin?
//
/// The C++ 'wchar_t' type.
public typealias CWideChar = Unicode.Scalar
// FIXME: Swift should probably have a UTF-16 type other than UInt16.
//
/// The C++11 'char16_t' type, which has UTF-16 encoding.
public typealias CChar16 = UInt16
/// The C++11 'char32_t' type, which has UTF-32 encoding.
public typealias CChar32 = Unicode.Scalar
/// The C '_Bool' and C++ 'bool' type.
public typealias CBool = Bool
/// A wrapper around an opaque C pointer.
///
/// Opaque pointers are used to represent C pointers to types that
/// cannot be represented in Swift, such as incomplete struct types.
@_fixed_layout
public struct OpaquePointer : Hashable {
@_versioned
internal var _rawValue: Builtin.RawPointer
@_versioned
@_transparent
internal init(_ v: Builtin.RawPointer) {
self._rawValue = v
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: Int) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Creates an `OpaquePointer` from a given address in memory.
@_transparent
public init?(bitPattern: UInt) {
if bitPattern == 0 { return nil }
self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue)
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
@_transparent
public init<T>(_ from: UnsafePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(_ from: UnsafePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
@_transparent
public init<T>(_ from: UnsafeMutablePointer<T>) {
self._rawValue = from._rawValue
}
/// Converts a typed `UnsafeMutablePointer` to an opaque C pointer.
///
/// The result is `nil` if `from` is `nil`.
@_transparent
public init?<T>(_ from: UnsafeMutablePointer<T>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// The pointer's hash value.
///
/// The hash value is not guaranteed to be stable across different
/// invocations of the same program. Do not persist the hash value across
/// program runs.
public var hashValue: Int {
return Int(Builtin.ptrtoint_Word(_rawValue))
}
}
extension OpaquePointer : CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
extension Int {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension UInt {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
public init(bitPattern pointer: OpaquePointer?) {
self.init(bitPattern: UnsafeRawPointer(pointer))
}
}
extension OpaquePointer : Equatable {
public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
/// The corresponding Swift type to `va_list` in imported C APIs.
@_fixed_layout
public struct CVaListPointer {
var value: UnsafeMutableRawPointer
public // @testable
init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) {
value = from
}
}
extension CVaListPointer : CustomDebugStringConvertible {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return value.debugDescription
}
}
@_versioned
@_inlineable
func _memcpy(
dest destination: UnsafeMutableRawPointer,
src: UnsafeMutableRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memcpy_RawPointer_RawPointer_Int64(
dest, src, size,
/*alignment:*/ Int32()._value,
/*volatile:*/ false._value)
}
/// Copy `count` bytes of memory from `src` into `dest`.
///
/// The memory regions `source..<source + count` and
/// `dest..<dest + count` may overlap.
@_versioned
@_inlineable
func _memmove(
dest destination: UnsafeMutableRawPointer,
src: UnsafeRawPointer,
size: UInt
) {
let dest = destination._rawValue
let src = src._rawValue
let size = UInt64(size)._value
Builtin.int_memmove_RawPointer_RawPointer_Int64(
dest, src, size,
/*alignment:*/ Int32()._value,
/*volatile:*/ false._value)
}
| apache-2.0 | 0230fa31ea8d46e04076591154263f1b | 27.234568 | 80 | 0.672059 | 4.148126 | false | false | false | false |
alobanov/Dribbble | Dribbble/services/schedulers/RxSchedulers.swift | 1 | 1016 | //
// RxSchedulers.swift
// Dribbble
//
// Created by Lobanov Aleksey on 09.08.16.
// Copyright © 2016 Lobanov Aleksey. All rights reserved.
//
import Foundation
import RxSwift
class Schedulers {
static let shared = Schedulers() // Singletone
let backgroundWorkScheduler: ImmediateSchedulerType
let mainScheduler: SerialDispatchQueueScheduler
let queueRequestNetwork: DispatchQueue! // single
let backgroundQueue: DispatchQueue! // single
private init() {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.qualityOfService = QualityOfService.userInitiated
backgroundWorkScheduler = OperationQueueScheduler(operationQueue: operationQueue)
queueRequestNetwork = DispatchQueue(label: "ru.dribbble", attributes: DispatchQueue.Attributes.concurrent)
mainScheduler = MainScheduler.instance
backgroundQueue = DispatchQueue(label: "ru.dribbble.lobanov", qos: .background, attributes: [.concurrent])
}
}
| mit | b9be29595dd7c8d8c899d984dac5969a | 29.757576 | 110 | 0.761576 | 5.205128 | false | false | false | false |
quran/quran-ios | Sources/Preferences/PreferenceKey.swift | 1 | 780 | //
// PreferenceKey.swift
//
//
// Created by Mohamed Afifi on 2021-12-17.
//
import Foundation
#if DEBUG
private struct Statics {
static var registeredKeys = Set<String>()
}
#endif
public final class PreferenceKey<Type> {
public let key: String
public let defaultValue: Type
public init(key: String, defaultValue: Type) {
self.key = key
self.defaultValue = defaultValue
#if DEBUG
if Statics.registeredKeys.contains(key) {
fatalError("PersistenceKey '\(key)' is registered multiple times")
}
Statics.registeredKeys.insert(key)
#endif
}
init(_ key: String, _ defaultValue: Type) {
self.key = key
self.defaultValue = defaultValue
}
}
| apache-2.0 | 6d70b8844d2d94b3a26babdeb678aa25 | 20.666667 | 82 | 0.60641 | 4.285714 | false | false | false | false |
blinksh/blink | KB/Native/Views/General/FixedTextField.swift | 1 | 6602 | //////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Blink is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import SwiftUI
struct FixedTextField: UIViewRepresentable {
class ViewWrapper: UIView, UITextFieldDelegate {
let textField = UITextField()
fileprivate let _id: String
fileprivate let _nextId: String?
fileprivate let _returnKeyType: UIReturnKeyType?
fileprivate let _onReturn: (() -> ())?
fileprivate let _enabled: Bool
@Binding var text: String
init(
_ placeholder: String,
text: Binding<String>,
id: String = UUID().uuidString,
nextId: String?,
returnKeyType: UIReturnKeyType? = nil,
onReturn: (() -> ())? = nil,
secureTextEntry: Bool = false,
keyboardType: UIKeyboardType,
autocorrectionType: UITextAutocorrectionType = .default,
autocapitalizationType: UITextAutocapitalizationType = .sentences,
enabled: Bool = true
) {
_id = id
_text = text
_nextId = nextId
_returnKeyType = returnKeyType
_onReturn = onReturn
_enabled = enabled
super.init(frame: .zero)
textField.keyboardType = keyboardType
textField.placeholder = placeholder
textField.delegate = self
textField.isSecureTextEntry = secureTextEntry
textField.isEnabled = enabled
textField.addTarget(
self,
action: #selector(ViewWrapper._changed(sender:)),
for: UIControl.Event.editingChanged
)
textField.autocorrectionType = autocorrectionType
textField.autocapitalizationType = autocapitalizationType
self.addSubview(textField)
if let returnKeyType = returnKeyType {
textField.returnKeyType = returnKeyType
} else if _nextId != nil {
textField.returnKeyType = .next
}
}
override func becomeFirstResponder() -> Bool {
return textField.becomeFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if let onReturn = _onReturn {
textField.resignFirstResponder()
onReturn()
return false
}
if let nextId = _nextId,
let nextField = ViewWrapper.__map[nextId] {
nextField.becomeFirstResponder()
} else {
textField.resignFirstResponder()
}
return false
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if superview == nil {
ViewWrapper.__map.removeValue(forKey: _id)
} else {
ViewWrapper.__map[_id] = self
}
}
@objc func _changed(sender: UITextField) {
text = sender.text ?? ""
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
textField.frame = bounds
}
static var __map:[String: UIView] = [:]
}
private let _placeholder: String
@Binding private var text: String
private let _id: String
private let _nextId: String?
private let _returnKeyType: UIReturnKeyType?
private let _onReturn: (() -> ())?
private let _keyboardType: UIKeyboardType
private let _autocorrectionType: UITextAutocorrectionType
private let _autocapitalizationType: UITextAutocapitalizationType
private let _secureTextEntry: Bool
private let _enabled: Bool
init(
_ placeholder: String,
text: Binding<String>,
id: String,
nextId: String? = nil,
returnKeyType: UIReturnKeyType? = nil,
onReturn: (() -> ())? = nil,
secureTextEntry: Bool = false,
keyboardType: UIKeyboardType = .default,
autocorrectionType: UITextAutocorrectionType = .default,
autocapitalizationType: UITextAutocapitalizationType = .sentences,
enabled: Bool = true
) {
_placeholder = placeholder
_text = text
_id = id
_nextId = nextId
_returnKeyType = returnKeyType
_onReturn = onReturn
_secureTextEntry = secureTextEntry
_keyboardType = keyboardType
_autocorrectionType = autocorrectionType
_autocapitalizationType = autocapitalizationType
_enabled = enabled
}
func makeUIView(
context: UIViewRepresentableContext<FixedTextField>
) -> ViewWrapper {
ViewWrapper(
_placeholder,
text: _text,
id: _id,
nextId: _nextId,
returnKeyType: _returnKeyType,
onReturn: _onReturn,
secureTextEntry: _secureTextEntry,
keyboardType: _keyboardType,
autocorrectionType: _autocorrectionType,
autocapitalizationType: _autocapitalizationType
)
}
static func dismantleUIView(_ uiView: ViewWrapper, coordinator: ()) {
uiView.textField.removeTarget(
nil, action: nil, for: UIControl.Event.editingChanged
)
uiView.textField.delegate = nil
}
func updateUIView(
_ uiView: ViewWrapper,
context: UIViewRepresentableContext<FixedTextField>
) {
uiView.textField.placeholder = _placeholder
uiView.textField.autocapitalizationType = _autocapitalizationType
uiView.textField.autocorrectionType = _autocorrectionType
uiView.textField.isSecureTextEntry = _secureTextEntry
uiView.textField.isEnabled = _enabled
if !uiView.textField.isFirstResponder {
uiView.textField.text = text
}
}
static func becomeFirstReponder(id: String) {
DispatchQueue.main.async() {
ViewWrapper.__map[id]?.becomeFirstResponder()
}
}
}
| gpl-3.0 | 8bae978f12c2501c0ce4b45957847d76 | 29.564815 | 82 | 0.65571 | 5.125776 | false | false | false | false |
HarrisLee/SwiftBook | SmartHomeI/SmartHomeI/Modules/MeModule/Me/View/MeHeaderView.swift | 1 | 5789 | //
// MeHeaderView.swift
// SmartHomeI
//
// Created by JianRongCao on 02/06/2017.
// Copyright © 2017 JianRongCao. All rights reserved.
//
import UIKit
import Kingfisher
public typealias headerClick = ((_ identifier:Int)->())
class MeHeaderView: UIView {
var line : UIView!
var backgroundImage:UIImageView!
var horLine : UIView!
var verLine : UIView!
var iconView : UIImageView!;
var nameLabel : UILabel!;
var seceneButton : UIButton!;
var msgButton : UIButton!;
var unreadView : UIView!;
var clickBlock : headerClick!;
override init(frame: CGRect) {
super.init(frame: frame);
self.backgroundColor = ME_COLOR;
self.setUpView();
}
func setUpView() {
backgroundImage = UIImageView.init(image: #imageLiteral(resourceName: "me_icon_bgview.png"));
backgroundImage.contentMode = .scaleAspectFill;
backgroundImage.clipsToBounds = true;
self.addSubview(backgroundImage);
backgroundImage.snp.makeConstraints { (make) in
make.left.right.equalTo(self);
make.bottom.equalTo(self).offset(-20);
};
horLine = UIView.init();
horLine.backgroundColor = RBGAWhite(white: 1.0, alpha: 0.5);
self.addSubview(horLine);
horLine.snp.makeConstraints { (make) in
make.height.equalTo(0.5);
make.left.width.equalTo(self);
make.bottom.equalTo(self).offset(-65);
};
verLine = UIView.init();
verLine.backgroundColor = RBGAWhite(white: 1.0, alpha: 0.5);
self.addSubview(verLine);
verLine.snp.makeConstraints { (make) in
make.centerX.equalTo(self);
make.width.equalTo(0.5);
make.top.equalTo(horLine.snp.bottom);
make.bottom.equalTo(self).offset(-20);
};
seceneButton = UIButton.init(type: .custom);
seceneButton.tag = 1000;
seceneButton.setTitle("智能场景", for: .normal);
seceneButton.setImage(UIImage.init(named: "me_icon_secene"), for: .normal);
seceneButton.titleLabel?.font = RM_FONT_28PX;
seceneButton.setTitleColor(UIColor.white, for: .normal);
seceneButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0);
seceneButton.addTarget(self, action: #selector(self.itemClick(identifier:)), for: .touchUpInside);
self.addSubview(seceneButton);
seceneButton.snp.makeConstraints { (make) in
make.left.bottom.equalTo(backgroundImage);
make.width.equalTo(kSCREEN_WIDTH/2.0);
make.height.equalTo(45);
};
msgButton = UIButton.init(type: .custom);
msgButton.tag = 2000;
msgButton.setTitle("消息中心", for: .normal);
msgButton.setImage(UIImage.init(named: "me_icon_mycenter"), for: .normal);
msgButton.titleLabel?.font = RM_FONT_28PX;
msgButton.setTitleColor(UIColor.white, for: .normal);
msgButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 10, bottom: 0, right: 0);
msgButton.addTarget(self, action: #selector(self.itemClick(identifier:)), for: .touchUpInside);
self.addSubview(msgButton);
msgButton.snp.makeConstraints { (make) in
make.left.equalTo(seceneButton.snp.right).offset(0.5);
make.top.width.height.equalTo(seceneButton);
};
unreadView = UIView.init();
unreadView.layer.cornerRadius = 2.5;
unreadView.backgroundColor = UIColor.red;
self.addSubview(unreadView);
unreadView.snp.makeConstraints { (make) in
make.height.width.equalTo(5);
make.left.equalTo(msgButton.snp.centerX).offset(40);
make.top.equalTo(self.snp.bottom).offset(-55);
}
nameLabel = UILabel.init();
nameLabel.textColor = UIColor.white;
nameLabel.font = RM_FONT_26PX;
nameLabel.textAlignment = .center;
nameLabel.text = "欢迎登录,乐享自在生活";
self.addSubview(nameLabel);
nameLabel.snp.makeConstraints { (make) in
make.left.centerX.equalTo(self);
make.bottom.equalTo(horLine.snp.top).offset(-20);
}
iconView = UIImageView.init(image: UIImage.init(named: "me_icon_unlogin"));
iconView.tag = 3000;
iconView.layer.cornerRadius = 40;
iconView.clipsToBounds = true;
iconView.isUserInteractionEnabled = true;
self.addSubview(iconView);
iconView.snp.makeConstraints { (make) in
make.width.height.equalTo(80);
make.bottom.equalTo(nameLabel.snp.top).offset(-10);
make.centerX.equalTo(self);
}
let ges = UITapGestureRecognizer.init(target: self, action: #selector(self.headerClick(ges:)));
iconView.addGestureRecognizer(ges);
// let source = ImageResource.init(downloadURL: URL.init(string: "wwwww")!);
// iconView.kf.setImage(with: source);
// let add: (Int,Int)->Int = {
// (a,b) in return a+b;
// };
//
// let bl : headerClick = {
// param in
// print(param);
// }
// bl("user");
// print(add(2,5));
}
func item(click:@escaping headerClick) {
self.clickBlock = click;
}
func headerClick(ges:UIGestureRecognizer) -> Void {
self.clickBlock((ges.view?.tag)!);
}
func itemClick(identifier:UIButton) -> Void {
self.clickBlock(identifier.tag);
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 740a286c96e2dbab61f6f78a270c6767 | 34.276074 | 106 | 0.599652 | 4.043601 | false | false | false | false |
IAskWind/IAWExtensionTool | IAWExtensionTool/IAWExtensionTool/Classes/Tool/IAW_ImgXcassetsTool.swift | 1 | 785 | //
// IAWXcassetsTool.swift
// IAWExtensionTool
//
// Created by winston on 16/11/17.
// Copyright © 2016年 winston. All rights reserved.
//
import Foundation
public enum IAW_ImgXcassetsTool: String {
case defaultInfo = "defaultInfo"
case errorInfo = "errorInfo"
case successInfo = "successInfo"
case headerPhoto = "headerPhoto"
case v2_refreshWhite = "v2_refreshWhite"
case back_9x15 = "back_9x15"
case not_network_loading_226x119 = "not_network_loading_226x119"
case iaw_snow = "iaw_snow"
case ic_menu_black_24dp = "ic_menu_black_24dp"
case cehua = "cehua"
/// Returns the associated image.
public var image: UIImage {
return UIImage(named: rawValue, in: Bundle.iawframeworkBundle(), compatibleWith: nil)!
}
}
| mit | 7f29f52fef0a40955f3055fe9ae9ae72 | 27.962963 | 94 | 0.681586 | 3.313559 | false | false | false | false |
morgz/SwiftGoal | SwiftGoal/Views/RankingCell.swift | 3 | 1408 | //
// RankingCell.swift
// SwiftGoal
//
// Created by Martin Richter on 23/07/15.
// Copyright (c) 2015 Martin Richter. All rights reserved.
//
import UIKit
class RankingCell: UITableViewCell {
let playerNameLabel: UILabel
let ratingLabel: UILabel
// MARK: Lifecycle
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
playerNameLabel = UILabel()
playerNameLabel.font = UIFont(name: "OpenSans", size: 19)
ratingLabel = UILabel()
ratingLabel.font = UIFont(name: "OpenSans", size: 19)
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(playerNameLabel)
contentView.addSubview(ratingLabel)
makeConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: Layout
private func makeConstraints() {
let superview = self.contentView
playerNameLabel.snp_makeConstraints { make in
make.leading.equalTo(superview.snp_leadingMargin)
make.centerY.equalTo(superview.snp_centerY)
}
ratingLabel.snp_makeConstraints { make in
make.leading.equalTo(playerNameLabel.snp_trailingMargin)
make.trailing.equalTo(superview.snp_trailingMargin)
make.centerY.equalTo(superview.snp_centerY)
}
}
}
| mit | 9092592418054eff58e51c0c5928c86b | 25.566038 | 74 | 0.662642 | 4.693333 | false | false | false | false |
morgz/SwiftGoal | SwiftGoal/Models/Ranking.swift | 1 | 1413 | //
// Ranking.swift
// SwiftGoal
//
// Created by Martin Richter on 24/07/15.
// Copyright (c) 2015 Martin Richter. All rights reserved.
//
import Argo
struct Ranking {
let player: Player
let rating: Float
static func contentMatches(lhs: Ranking, _ rhs: Ranking) -> Bool {
return Player.contentMatches(lhs.player, rhs.player)
&& lhs.rating == rhs.rating
}
static func contentMatches(lhs: [Ranking], _ rhs: [Ranking]) -> Bool {
// Make sure arrays have same size
guard lhs.count == rhs.count else { return false }
// Look at pairs of rankings
let hasMismatch = zip(lhs, rhs)
.map { contentMatches($0, $1) } // Apply content matcher to each
.contains(false) // Check for mismatches
return !hasMismatch
}
}
// MARK: Equatable
func ==(lhs: Ranking, rhs: Ranking) -> Bool {
return lhs.player == rhs.player
}
// MARK: Decodable
extension Ranking: Decodable {
static func create(player: Player)(rating: Float) -> Ranking {
return Ranking(player: player, rating: rating)
}
static func decode(json: JSON) -> Decoded<Ranking> {
return Ranking.create
<^> json <| "player"
<*> json <| "rating"
}
}
// MARK: Hashable
extension Ranking: Hashable {
var hashValue: Int {
return player.identifier.hashValue ^ rating.hashValue
}
}
| mit | 86ce52ff8e6b5ea3fc6bf195c7d301b2 | 23.362069 | 76 | 0.610757 | 3.980282 | false | false | false | false |
dipen30/Qmote | KodiRemote/KodiRemote/Controllers/RemoteController.swift | 1 | 12372 | //
// RemoteController.swift
// Kodi Remote
//
// Created by Quixom Technology on 18/12/15.
// Copyright © 2015 Quixom Technology. All rights reserved.
//
import Foundation
import Kingfisher
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
class RemoteController: ViewController {
@IBOutlet var itemName: UILabel!
@IBOutlet var otherDetails: UILabel!
@IBOutlet var activePlayerImage: UIImageView!
@IBOutlet var nothingPlaying: UILabel!
@IBOutlet var play: UIButton!
@IBOutlet var pause: UIButton!
@IBOutlet var timeLabel: UILabel!
@IBOutlet var totalTimeLabel: UILabel!
@IBOutlet var seekBar: UISlider!
var playerId = 0
var player_repeat = "off"
var shuffle = false
@IBOutlet var musicButtonLeadingSpace: NSLayoutConstraint!
@IBOutlet var videoButtonTrailingSpace: NSLayoutConstraint!
@IBOutlet var repeatButtonLeadingSpace: NSLayoutConstraint!
@IBOutlet var volumUpLeadingSpace: NSLayoutConstraint!
@IBOutlet var playerRepeat: UIButton!
@IBOutlet var playerShuffle: UIButton!
@IBOutlet weak var backgroundImage: UIImageView!
var rc: RemoteCalls!
override func viewDidLoad() {
super.viewDidLoad()
self.view.addGestureRecognizer(self.revealViewController().tapGestureRecognizer())
}
override func viewDidAppear(_ animated: Bool) {
self.view.viewWithTag(2)?.isHidden = true
self.backgroundImage.layer.opacity = 0.1
self.view.viewWithTag(2)?.layer.opacity = 0.9
self.view.viewWithTag(1)?.layer.opacity = 0.9
let previous_ip = UserDefaults.standard
if let ip = previous_ip.string(forKey: "ip"){
global_ipaddress = ip
}
if let port = previous_ip.string(forKey: "port"){
global_port = port
}
if global_ipaddress == "" {
let discovery = self.storyboard?.instantiateViewController(withIdentifier: "DiscoveryView") as! DiscoveryTableViewController
self.navigationController?.pushViewController(discovery, animated: true)
}
if global_ipaddress != "" {
rc = RemoteCalls(ipaddress: global_ipaddress, port: global_port)
self.syncPlayer()
}
}
func syncPlayer(){
self.rc.jsonRpcCall("Player.GetActivePlayers"){(response: AnyObject?) in
if response!.count == 0 {
DispatchQueue.main.async(execute: {
self.view.viewWithTag(2)?.isHidden = true
self.nothingPlaying.isHidden = false
self.backgroundImage.isHidden = true
})
return
}
DispatchQueue.main.async(execute: {
self.view.viewWithTag(2)?.isHidden = false
self.nothingPlaying.isHidden = true
self.backgroundImage.isHidden = false
})
let response = (response as! NSArray)[0] as? NSDictionary
self.playerId = response!["playerid"] as! Int
self.rc.jsonRpcCall("Player.GetProperties", params: "{\"playerid\":\(self.playerId),\"properties\":[\"percentage\",\"time\",\"totaltime\", \"repeat\",\"shuffled\",\"speed\",\"subtitleenabled\"]}"){(response: AnyObject?) in
DispatchQueue.main.async(execute: {
let response = response as? NSDictionary
self.shuffle = response!["shuffled"] as! Bool
self.player_repeat = response!["repeat"] as! String
let repeateImage = self.player_repeat == "off" ? "Repeat": "RepeatSelected"
self.playerRepeat.imageView?.image = UIImage(named: repeateImage)
let suffleImage = self.shuffle == true ? "shuffleSelected" : "shuffle"
self.playerShuffle.imageView?.image = UIImage(named: suffleImage)
if response!["speed"] as! Int == 0 {
self.play.isHidden = false
self.pause.isHidden = true
}else{
self.play.isHidden = true
self.pause.isHidden = false
}
self.timeLabel.text = self.toMinutes(response!["time"] as! NSDictionary)
self.totalTimeLabel.text = self.toMinutes(response!["totaltime"] as! NSDictionary)
self.seekBar.value = (response!["percentage"] as! Float) / 100
})
self.rc.jsonRpcCall("Player.GetItem", params: "{\"playerid\":\(self.playerId),\"properties\":[\"title\",\"artist\",\"thumbnail\", \"fanart\", \"album\",\"year\"]}"){(response: AnyObject?) in
DispatchQueue.main.async(execute: {
let response = response as? NSDictionary
self.generateResponse(response!)
});
}
}
}
// 1 second trigger Time
let triggerTime = Int64(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(triggerTime) / Double(NSEC_PER_SEC), execute: { () -> Void in
self.syncPlayer()
})
}
@IBAction func sliderTouchUp(_ sender: UISlider) {
// RPC call for seek
let value = Int(sender.value * 100)
self.seekBar.value = sender.value
rc.jsonRpcCall("Player.Seek", params: "{\"playerid\":\(self.playerId), \"value\":\(value)}"){(response: AnyObject?) in
}
}
func generateResponse(_ jsonData: AnyObject){
for(key, value) in jsonData["item"] as! NSDictionary{
if key as! String == "label" {
self.itemName.text = value as? String
}
if key as! String == "artist" {
self.otherDetails.text = ""
if (value as AnyObject).count != 0 {
self.otherDetails.text = (value as! NSArray)[0] as? String
}
}
if key as! String == "thumbnail" {
self.activePlayerImage.contentMode = .scaleAspectFit
let url = URL(string: getThumbnailUrl(value as! String))
self.activePlayerImage.kf.setImage(with: url!)
}
if key as! String == "fanart" {
self.backgroundImage.contentMode = .scaleAspectFill
let url = URL(string: getThumbnailUrl(value as! String))
self.backgroundImage.kf.setImage(with: url!)
}
}
}
func toMinutes(_ temps: NSDictionary ) -> String {
var seconds = String(temps["seconds"] as! Int)
var minutes = String(temps["minutes"] as! Int)
var hours = String(temps["hours"] as! Int)
if (Int(seconds) < 10) {
seconds = "0" + seconds
}
if (Int(minutes) < 10) {
minutes = "0" + minutes
}
if (Int(hours) < 10) {
hours = "0" + hours
}
var time = minutes + ":" + seconds
if Int(hours) != 0 {
time = hours + ":" + minutes + ":" + seconds
}
return time
}
@IBAction func previousButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"skipprevious\"}"){(response: AnyObject?) in
}
}
@IBAction func fastRewindButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stepback\"}"){(response: AnyObject?) in
}
}
@IBAction func stopButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stop\"}"){(response: AnyObject?) in
}
}
@IBAction func playButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"play\"}"){(response: AnyObject?) in
}
}
@IBAction func pauseButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"pause\"}"){(response: AnyObject?) in
}
}
@IBAction func fastForwardButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"stepforward\"}"){(response: AnyObject?) in
}
}
@IBAction func nextButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"skipnext\"}"){(response: AnyObject?) in
}
}
@IBAction func leftButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Left"){(response: AnyObject?) in
}
}
@IBAction func rightButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Right"){(response: AnyObject?) in
}
}
@IBAction func downButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Down"){(response: AnyObject?) in
}
}
@IBAction func upButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Up"){(response: AnyObject?) in
}
}
@IBAction func okButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Select"){(response: AnyObject?) in
}
}
@IBAction func homeButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Home"){(response: AnyObject?) in
}
}
@IBAction func backButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Back"){(response: AnyObject?) in
}
}
@IBAction func tvButton(_ sender: AnyObject) {
rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"videos\",\"parameters\":[\"TvShowTitles\"]}"){(response: AnyObject?) in
}
}
@IBAction func moviesButton(_ sender: AnyObject) {
rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"video\",\"parameters\":[\"MovieTitles\"]}"){(response: AnyObject?) in
}
}
@IBAction func musicButton(_ sender: AnyObject) {
rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"music\"}"){(response: AnyObject?) in
}
}
@IBAction func pictureButton(_ sender: AnyObject) {
rc.jsonRpcCall("GUI.ActivateWindow", params: "{\"window\": \"pictures\"}"){(response: AnyObject?) in
}
}
@IBAction func volumeDownButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"volumedown\"}"){(response: AnyObject?) in
}
}
@IBAction func muteButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"mute\"}"){(response: AnyObject?) in
}
}
@IBAction func volumeUpButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ExecuteAction", params: "{\"action\":\"volumeup\"}"){(response: AnyObject?) in
}
}
@IBAction func repeatButton(_ sender: AnyObject) {
let r = self.player_repeat == "off" ? "all" : "off"
rc.jsonRpcCall("Player.SetRepeat", params: "{\"playerid\":\(self.playerId), \"repeat\":\"\(r)\"}"){(response: AnyObject?) in
}
}
@IBAction func shuffleButton(_ sender: AnyObject) {
let s = self.shuffle == true ? "false": "true"
rc.jsonRpcCall("Player.SetShuffle", params: "{\"playerid\":\(self.playerId), \"shuffle\":\(s)}"){(response: AnyObject?) in
}
}
@IBAction func osdButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ShowOSD"){(response: AnyObject?) in
}
}
@IBAction func contextButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.ContextMenu"){(response: AnyObject?) in
}
}
@IBAction func infoButton(_ sender: AnyObject) {
rc.jsonRpcCall("Input.Info"){(response: AnyObject?) in
}
}
}
| apache-2.0 | 45c61e67886986298521188ce1f7cc13 | 34.245014 | 234 | 0.547005 | 4.748944 | false | false | false | false |
oacastefanita/PollsFramework | Example/PollsFramework/ViewControllers/LoginViewController.swift | 1 | 5087 | //
// LoginViewController.swift
// PollsFramework
//
// Created by oacastefanita on 06/27/2017.
// Copyright (c) 2017 oacastefanita. All rights reserved.
//
import UIKit
import PollsFramework
import CoreData
import WatchConnectivity
class LoginViewController: UIViewController, ViewObjectDelegate, UITextFieldDelegate {
@IBOutlet weak var txtUsername: UITextField!
@IBOutlet weak var txtPassword: UITextField!
@IBOutlet weak var switchIsPartner: UISwitch!
var login: LoginStruct!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.login = LoginStruct()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onSignup(_ sender: Any) {
self.view.endEditing(true)
self.performSegue(withIdentifier: "showCreateRegisterFromLogin", sender: self)
}
@IBAction func onLogin(_ sender: Any) {
self.view.endEditing(true)
fillViewModel()
PollsFrameworkController.sharedInstance.login(login: self.login){ (success, response) in
if !success {
}
else {
self.performSegue(withIdentifier: "showHomeFromLogin", sender: self)
}
}
}
@IBAction func onAddDevice(_ sender: Any) {
// self.view.endEditing(true)
// self.checkAndCreateDevice()
// self.performSegue(withIdentifier: "showCreateDeviceFromLogin", sender: self)
}
@IBAction func onAutofillDevice(_ sender: Any) {
self.checkAndCreateDevice()
// login.newDevice?.browserName = "iOS Phone not a browser"
// login.newDevice?.browserVersion = "iOS Phone not a browser"
// login.newDevice?.browserUserAgent = "iOS Phone not a browser"
// login.newDevice?.deviceName = UIDevice.current.name
// login.newDevice?.deviceVersion = UIDevice.current.systemVersion
// login.newDevice?.devicePlatform = "iOS"
// login.newDevice?.snsType = "APNS"
// login.newDevice?.snsDeviceId = APP_SESSION.pushNotificationsToken
// login.newDevice?.channelId = "None"
}
func checkAndCreateDevice(){
// if loginViewModel.newDevice == nil{
// var newDevice = (NSEntityDescription.insertNewObject(forEntityName: "Device", into: PollsFrameworkController.sharedInstance.dataController().managedObjectContext) as! Device)
// login.newDevice = newDevice
// }
}
@IBAction func onResetPassword(_ sender: Any) {
self.performSegue(withIdentifier: "showForgotPasswordFromLogin", sender: self)
}
func editedObject(object: NSObject, objectType: ObjectTypes?) {
if objectType == .device{
PollsFrameworkController.sharedInstance.device = object as? Device
} else if objectType == .register{
PollsFrameworkController.sharedInstance.register(register: (object as? RegisterStruct)!, contact: ContactStruct()){ (success, response) in
if !success {
}
else {
self.performSegue(withIdentifier: "showHomeFromLogin", sender: self)
}
}
}
}
func fillViewModel(){
self.login.username = txtUsername.text!
self.login.password = txtPassword.text!
self.login.isPartner = switchIsPartner.isOn
// self.loginViewModel.deviceId = UUID().uuidString
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showCreateDeviceFromLogin"{
((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).objectType = .device
((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).object = PollsFrameworkController.sharedInstance.device
((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).delegate = self
((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).screenType = .edit
} else if segue.identifier == "showCreateRegisterFromLogin"{
((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).objectType = .register
((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).object = RegisterStruct()
((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).delegate = self
((segue.destination as! UINavigationController).viewControllers.first as! ViewObjectViewController).screenType = .edit
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.endEditing(true)
return true
}
}
| mit | 237d582f218d110142c0fde53885ded2 | 40.696721 | 188 | 0.668764 | 5.001967 | false | false | false | false |
TH-Brandenburg/University-Evaluation-iOS | EdL/QuestionController.swift | 1 | 6297 | //
// QuestionController.swift
// EdL
//
// Created by Daniel Weis on 18.06.16.
//
//
import UIKit
import SwiftyJSON
import AKPickerView_Swift
/// This class controls the PageViewController and creates ViewControllers for each question
class QuestionController: NSObject, UIPageViewControllerDataSource, AKPickerViewDataSource {
var questions: QuestionsDTO
var answers: AnswersDTO
let otherPagesCount = 2
enum QuestionType {
case MultipleChoice
case Text
case StudyPath
case Completion
}
init(questions: QuestionsDTO, answers: AnswersDTO) {
self.questions = questions
self.answers = answers
super.init()
}
func viewControllerAtIndex(index: Int, storyboard: UIStoryboard) -> UIViewController? {
// Return the data view controller for the given index.
// Create a new view controller and pass suitable data.
if index == 0 {
return createViewController(.StudyPath, index: index, localIndex: index, storyboard: storyboard)
} else if index == questions.textQuestions.count + questions.multipleChoiceQuestions.count + otherPagesCount - 1 {
return createViewController(.Completion, index: index, localIndex: index, storyboard: storyboard)
} else if questions.textQuestionsFirst {
if index < questions.textQuestions.count + 1 {
return createViewController(.Text, index: index, localIndex: index - 1, storyboard: storyboard)
} else {
return createViewController(.MultipleChoice, index: index, localIndex: index - questions.textQuestions.count - 1, storyboard: storyboard)
}
} else {
if index < questions.multipleChoiceQuestions.count + 1 {
return createViewController(.MultipleChoice, index: index, localIndex: index - 1, storyboard: storyboard)
} else {
return createViewController(.Text, index: index, localIndex: index - questions.multipleChoiceQuestions.count - 1, storyboard: storyboard)
}
}
}
func createViewController(type: QuestionType, index: Int, localIndex: Int, storyboard: UIStoryboard) -> UIViewController? {
if type == .MultipleChoice{
let mcQuestionViewController = storyboard.instantiateViewControllerWithIdentifier("5Buttons") as! MultipleChoiceQuestionViewController
mcQuestionViewController.questionDTO = questions.multipleChoiceQuestions[localIndex]
mcQuestionViewController.answerDTO = answers.mcAnswers[localIndex]
mcQuestionViewController.index = index
mcQuestionViewController.localIndex = localIndex
return mcQuestionViewController
} else if type == .Text{
let textQuestionViewController = storyboard.instantiateViewControllerWithIdentifier("TextQuestion") as! TextQuestionViewController
textQuestionViewController.questionDTO = questions.textQuestions[localIndex]
textQuestionViewController.answerDTO = answers.textAnswers[localIndex]
textQuestionViewController.index = index
textQuestionViewController.localIndex = localIndex
return textQuestionViewController
} else if type == .StudyPath{
let studyPathViewController = storyboard.instantiateViewControllerWithIdentifier("StudyPath") as! StudyPathViewController
studyPathViewController.studyPaths = questions.studyPaths
studyPathViewController.answersDTO = answers
studyPathViewController.index = index
return studyPathViewController
} else if type == .Completion{
let completionViewController = storyboard.instantiateViewControllerWithIdentifier("Completion") as! CompletionViewController
completionViewController.answersDTO = answers
completionViewController.index = index
return completionViewController
}
return nil
}
func getIndex(viewController: UIViewController) -> Int {
if let questionViewController = viewController as? TextQuestionViewController{
return questionViewController.index
}
if let questionViewController = viewController as? MultipleChoiceQuestionViewController{
return questionViewController.index
}
if let questionViewController = viewController as? StudyPathViewController{
return questionViewController.index
}
if let questionViewController = viewController as? CompletionViewController{
return questionViewController.index
}
return -1
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = getIndex(viewController)
if (index == 0) || (index == -1) {
return nil
}
index -= 1
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = getIndex(viewController)
if index == -1 {
return nil
}
index += 1
if index == questions.multipleChoiceQuestions.count + questions.textQuestions.count + self.otherPagesCount {
return nil
}
return self.viewControllerAtIndex(index, storyboard: viewController.storyboard!)
}
// MARK: - AKPickerViewDataSource
func numberOfItemsInPickerView(pickerView: AKPickerView) -> Int {
return self.questions.multipleChoiceQuestions.count + self.questions.textQuestions.count + self.otherPagesCount
}
func pickerView(pickerView: AKPickerView, titleForItem item: Int) -> String {
if item == 0 {
return "Studiengang"
}
if item == self.numberOfItemsInPickerView(pickerView) - 1 {
return "Absenden"
}
return String(item)
}
}
| apache-2.0 | 4f9e237cec51b61fc53bfcde2787a2ea | 40.156863 | 161 | 0.673495 | 5.874067 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.